标签:result 时间复杂度 标准 hat ret linked 官方 sort har
schedule: 3 be done ,3 better than 99%
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
思路:先对所给序列进行排序,然后依次对小于target/2的数a,在有序序列中用二分查找找(target-a)
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> ivec=nums;
sort(ivec.begin(),ivec.end());
int h=target/2;//half
int n1,n2,i;
for(i=0;i<nums.size();i++)
{
if(ivec[i]<h)
{
if(binary_search(ivec.begin(),ivec.end(),target-ivec[i]))
break;
}
else if(ivec[i]==h)
{
if(target%2==0){//偶数
auto r=equal_range(ivec.begin(),ivec.end(),h);
if(r.second-r.first>1)
break;
}
else//奇数
{
break;
}
}
}
n1=ivec[i];
n2=target-n1;
vector<int>::iterator it1,it2;
it1=find(nums.begin(),nums.end(),n1);
if(n1==n2)
it2=find(it1+1,nums.end(),n2);
else
it2=find(nums.begin(),nums.end(),n2);
int p1=it1-nums.begin(),p2=it2-nums.begin();
vector<int> result={p1,p2};
return result;
}
};
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> nums1(nums);
sort(nums1.begin(),nums1.end());
vector<int> re;
int L = 0, R = nums.size()-1;
while(L<=R){
if(nums1[L]+nums1[R]<target)
L++;
else if(nums1[L]+nums1[R]>target)
R--;
else
break;
}
int len = nums.size();
for(int i = 0;i<len;i++){
if(nums[i]==nums1[L]||nums[i]==nums1[R])
re.push_back(i);
}
return re;
}
};
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
static int x=[](){//IO加速
std::ios::sync_with_stdio(false);
cin.tie(NULL);
return 0;
}();
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* ls=l1,*lsp;//sum,sum‘s parent
int sum,c(0),t1,t2;
while(l2!=NULL || ls!=NULL || c!=0)
{
t1=(ls==NULL)?0:ls->val;
t2=(l2==NULL)?0:l2->val;
sum=t1+t2+c;
if(ls==NULL)
{
ListNode* s=new ListNode(sum%10);
ls=s;
lsp->next=s;
}
else
ls->val=sum%10;
c=sum/10;
lsp=ls;
if(ls!=NULL) ls=ls->next;
if(l2!=NULL) l2=l2->next;
}
return l1;
}
};
static int x=[](){//IO加速
std::ios::sync_with_stdio(false);
cin.tie(NULL);
return 0;
}();
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int i,j,maxLong;//i:当前子串起点,j:当前子串终点
int l[128];
for(i=0;i<128;l[i++]=-1);
for(i=0,j=0,maxLong=0;j<s.size();j++)
{
if(l[s[j]]!=-1 && l[s[j]]+1>i) i=l[s[j]]+1;
l[s[j]]=j;
if(j-i+1>maxLong) maxLong=j-i+1;
}
return maxLong;
}
};
标签:result 时间复杂度 标准 hat ret linked 官方 sort har
原文地址:https://www.cnblogs.com/yhjd/p/10209602.html