6.三数之和
大约 1 分钟
6.三数之和
参考链接
个人尝试(❌错误)
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
int i = 0;
int j = nums.length - 1;
while (i < j) {
// [-4, -1, -1, 0, 1, 2]
if (nums[i] + nums[j] < 0) {
int k = j - 1;
while (k > i) {
if (nums[i] + nums[k] + nums[j] == 0) {
res.add(new ArrayList<Integer>(Arrays.asList(nums[i], nums[k], nums[j])));
while (i < j && nums[i] == nums[i + 1]) i++;
break;
} else if (nums[i] + nums[k] + nums[j] > 0) {
k--;
} else {
break;
}
}
i++;
}
// [-1, -1, 0, 1, 2]
else {
int k = i + 1;
while (k < j) {
if (nums[i] + nums[k] + nums[j] == 0) {
res.add(new ArrayList<Integer>(Arrays.asList(nums[i], nums[k], nums[j])));
while (j > i && nums[j] == nums[j - 1]) j--;
break;
} else if (nums[i] + nums[k] + nums[j] > 0) {
break;
} else {
k++;
}
}
j--;
}
}
return res;
}
}
遇到 nums = [-1,0,1,2,-1,-4,-2,-3,3,0,4]
输出 [[-4,0,4],[-4,1,3],[-3,0,3],[-3,1,2],[-2,0,2],[-1,0,1]]
预期结果 [[-4,0,4],[-4,1,3],[-3,-1,4],[-3,0,3],[-3,1,2],[-2,-1,3],[-2,0,2],[-1,-1,2],[-1,0,1]]
优秀题解
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
n=len(nums)
res=[]
if(not nums or n<3):
return []
nums.sort()
res=[]
for i in range(n):
if(nums[i]>0):
return res
if(i>0 and nums[i]==nums[i-1]):
continue
L=i+1
R=n-1
while(L<R):
if(nums[i]+nums[L]+nums[R]==0):
res.append([nums[i],nums[L],nums[R]])
while(L<R and nums[L]==nums[L+1]):
L=L+1
while(L<R and nums[R]==nums[R-1]):
R=R-1
L=L+1
R=R-1
elif(nums[i]+nums[L]+nums[R]>0):
R=R-1
else:
L=L+1
return res
作者:吴彦祖
链接:https://leetcode.cn/problems/3sum/solutions/39722/pai-xu-shuang-zhi-zhen-zhu-xing-jie-shi-python3-by/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。