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的两个数字的 下标。
你可以假设每一组输入都恰好只有一个解。
例如:
给定数组 nums = [2, 7, 11, 15], target = 9, 因为 nums[0] + nums[1] = 2 + 7 = 9, 所以返回 [0, 1].
稍微做的有点麻烦。。。把原数组进行了排序并保存了一个原数组的copy,导致时间和空间复杂度都是O(n)。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> copy=nums;
sort(nums.begin(),nums.end());
vector<int> ans;
int left = 0 , right = nums.size() - 1;
while(left != right)
{
if(nums[left] + nums[right] == target) break;
if(nums[left] + nums[right] < target) left++;
else right--;
}
int i , j;
for(i=0 ; copy[i] != nums[left] ; i++);
for(j=nums.size()-1 ; copy[j] != nums[right] ; j--);
ans.push_back(i);
ans.push_back(j);
return ans;
}
};