1. 两数之和
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]
不能使用双指针方法,因为数组是无序的;虽然可以对数组排序,但是排序后的数组索引位置改变,而本题需要返回索引位置。
1 class Solution { 2 public: 3 vector<int> twoSum(vector<int>& nums, int target) { 4 vector<int> res; 5 sort(nums.begin(), nums.end()); //排序后索引位置就变了 6 int f=0,b=nums.size()-1; 7 while(f<b){ 8 if(nums[f]+nums[b]==target){ 9 return vector<int>{f,b}; 10 }else if(nums[f]+nums[b]>target){ 11 b--; 12 }else{ 13 f++; 14 } 15 } 16 return res; 17 } 18 };