1. 程式人生 > >1. Two Sum

1. Two Sum

break brush public qsort solution end ack size while

class Solution {
public:
//int compare(const void * arg1, const void *arg2)
//{
//return (*(int*)arg1 - *(int*)arg2);
//}
vector<int> twoSum(vector<int>& nums, int target) 
{
        vector<int> res;
        vector<int> temp=nums;
        int left;
        int right;
        
        sort(nums.begin(),nums.end(),less<int>());
        //qsort(nums.begin(), nums.size(), sizeof(int), compare);
        left=0;right=nums.size()-1;
        while(left!=right)
        {
        	if(nums[left]+nums[right]==target)
			{
                bool l=0,r=0;
				for(int i=0;i<nums.size();i++)
                {
                    if(temp[i]==nums[left])
                    {
                         res.push_back(i);
                        break;
                    }
                }
                for(int i=nums.size()-1;i>=0;i--)
                {
                    if(temp[i]==nums[right])
                    {
                        res.push_back(i);
                        break;
                    }
                }
				break;
			 } 
			 else  if(nums[left]+nums[right]>target)
			 {
			 	right--;
			 }
			 else
			 {
			 	left++;
			 }
		}
		return res;
}

};

  

1. Two Sum