[Lc]面试题57_I和为s的两个数字
Contents
题目
题解
可以用哈希表,但是需要用额外的存储空间,这道题有递增的性质,直接双指针,很简单,看代码就可以。
- 时间复杂度: $O(n)$
- 空间复杂度: $O(1)$
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int left = 0, right = nums.size() - 1;
while(left<right){
if(nums[left] + nums[right] < target) left++;
else if(nums[left] + nums[right] > target) right--;
else break;
}
return{nums[left], nums[right]};
}
};
``
Author ChrisHRZ
LastMod 2020-06-25