Two Sum
https://mp.weixin.qq.com/s?__biz=MzAxODQxMDM0Mw==&mid=2247484474&idx=1&sn=dfbadbe6e17d695a1907e2adcd9f0d3c&chksm=9bd7fa32aca0732406829a6d1de34b7e3144af239cc25e014f5349d73cea952d5f2b0473345a&scene=21#w
Last updated
https://mp.weixin.qq.com/s?__biz=MzAxODQxMDM0Mw==&mid=2247484474&idx=1&sn=dfbadbe6e17d695a1907e2adcd9f0d3c&chksm=9bd7fa32aca0732406829a6d1de34b7e3144af239cc25e014f5349d73cea952d5f2b0473345a&scene=21#w
Last updated
class TwoSum {
// 向数据结构中添加一个数 number
public void add(int number);
// 寻找当前数据结构中是否存在两个数的和为 value
public boolean find(int value);
}int[] twoSum(int[] nums, int target) {
int left = 0, right = nums.length - 1;
while (left < right) {
int sum = nums[left] + nums[right];
if (sum == target) {
return new int[]{left, right};
} else if (sum < target) {
left++; // 让 sum 大一点
} else if (sum > target) {
right--; // 让 sum 小一点
}
}
// 不存在这样两个数
return new int[]{-1, -1};
}