先放图:
先说传统的暴力解法,就是用双重循环,先固定一个数,然后从它后面的数字去找。时间复杂度为O(n^2),面试时肯定不行的。不过剑指说面试时有思路可以立即说出来,反映你思维敏捷。。
放下暴力解法代码:
class Solution {
public int[] twoSum(int[] nums, int target) {
if (nums == null) return null;
int l = 0, h = 0;
for (int i = 0; i <= nums.length - 2; i++) {
for (int j = i + 1; j <= nums.length - 1; j++) {
if ((nums[i] + nums[j]) == target) {
l = i;
h = j;
break;
}
}
}
return new int[] {nums[l], nums[h]};
}
}
接下来介绍面试解法:用双指针,初始时刻一个指向第一个数,另一个指针指向最后一个数(即最大的数)。用两个指针来判断,若和比target小,则逐渐增加较小的数;若和比target还大,则迅速减小较大的数。(指针移动的方向)
我的代码:
class Solution {
public int[] twoSum(int[] nums, int target) {
if (nums == null) return null;
int low = 0, high = nums.length - 1;
while (low < high) {
int tmp = nums[low] + nums[high];
if (tmp == target) break;
else if (tmp > target) high--;
else low++;
}
return new int[] {nums[low], nums[high]};
}
}
常见大佬的代码:
class Solution {
public int[] twoSum(int[] nums, int target) {
int i = 0, j = nums.length - 1;
while(i < j) {
int s = nums[i] + nums[j];
if(s < target) i++;
else if(s > target) j--;
else return new int[] { nums[i], nums[j] };
}
return new int[0];
}
}
作者:jyd
链接:https://leetcode-cn.com/problems/he-wei-sde-liang-ge-shu-zi-lcof/solution/mian-shi-ti-57-he-wei-s-de-liang-ge-shu-zi-shuang-/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
时间复杂度:O(n^2),空间复杂度:O(1)