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

1. Two Sum----LeetCode

1、Two Sum

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.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
題目:給定一個整數陣列,一個目標數 target,找出數組裡的兩個是使它們的和為target,返回這兩個數的角標indices
     假定每個輸入只有一個解
class Solution 
{
private:
    vector<int> GetIndex(const vector<int>& nums, int i1, int i2)
    {
        vector<int> result;
        for (int i=0; i<nums.size(); i++) {
            if (nums[i] == i1 || nums[i] == i2)
                result.push_back(i);
        }
        return result;
    }
public:
    vector<int> twoSum(vector<int> &numbers, int target) 
    {
        int n=numbers.size();
        vector<int>v(numbers.begin(),numbers.end());
        sort(v.begin(),v.end());

		int i=0, j = n-1;
		while(i<j){
		    int sum=v[i]+v[j];
		    if(sum<target)
		        i++;
		    else if(sum>target)
		        j--;
		    else 
		        break;
		}
		return GetIndex(numbers,v[i],v[j]);
    }
};