思路:注意递增序列,看到递增序列首先一般联想到双指针或者二分法。
class Solution {
public int[] twoSum(int[] nums, int target) {
int l = 0, r = nums.length - 1;
while (l < r){
if (nums[l] + nums[r] == target){
return new int[]{nums[l], nums[r]};
}else if (nums[l] + nums[r] < target){
l++;
}else {
r--;
}
}
return new int[0];
}
public int[] twoSum2(int[] nums, int target) {
Set<Integer> set = new HashSet<>();
for (int num : nums) {
set.add(num);
}
for (int num : nums) {
if (set.contains(target-num)){
return new int[]{num,target-num};
}
}
return new int[0];
}
}