LeetCode 15. 3Sum--Java,Python解法

LeetCode 15. 3Sum


LeetCode题解专栏:LeetCode题解
我做的所有的LeetCode的题目都放在这个专栏里,大部分题目Java和Python的解法都有。


Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

The solution set must not contain duplicate triplets.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

谷歌翻译的题目:
给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。

注意:

解决方案集不得包含重复的三元组。


我的思路是2重循环,算出a+b的所有可能,然后判断-(a+b)是否在列表里,时间复杂度是O(N^2)
Python解法:

class Solution:
    def threeSum(self, nums = [-4,-2,1,-5,-4,-4,4,-2,0,4,0,-2,3,1,-5,0]):
        nums.sort()
        length=len(nums)
        temp=[]
        temp4=set()
        a={}
        b={}
        for i in nums:
            if i not in a:
                a[i]=1
            else:
                a[i]+=1
        i=0
        while i<length:
            j=i+1
            while j<length:
                pass
                if j>=i+2 and nums[j]==nums[j-1]:
                    if nums[j]==nums[i]:
                        i=j-2
                        break
                    j+=1
                    continue
                if nums[i] not in b:
                    b[nums[i]]=set()
                if nums[j] in b[nums[i]]:
                    j+=1
                    continue
                else:
                    b[nums[i]].add(nums[j])
                temp2=-(nums[i]+nums[j])
                if temp2 in a :
                    count=1
                    if nums[i]==temp2:
                        count+=1
                    if nums[j]==temp2:
                        count+=1
                    if a[temp2]>=count:
                        temp3=[nums[i],nums[j],temp2]
                        temp3.sort()
                        if str(temp3) not in temp4:
                            temp4.add(str(temp3))
                            temp.append([nums[i],nums[j],temp2])
                j+=1
            i+=1                       
        for i in temp:
            i.sort()
        temp.sort()
        return temp

改进后的办法是两边向中间逼近:

class Solution:
    def threeSum(self, nums = [-4,-2,1,-5,-4,-4,4,-2,0,4,0,-2,3,1,-5,0]):
        res = []
        nums.sort()
        length = len(nums)
        for i in range(0,length-2): 
            if nums[i]>0: 
                break 
            if i>0 and nums[i]==nums[i-1]: 
                continue 
            l, r = i+1, length-1 
            while l<r:
                total = nums[i]+nums[l]+nums[r]
                if total<0:
                    l+=1
                elif total>0: 
                    r-=1
                else: 
                    res.append([nums[i], nums[l], nums[r]])
                    while l<r and nums[l]==nums[l+1]:
                        l+=1
                    while l<r and nums[r]==nums[r-1]: 
                        r-=1
                    l+=1
                    r-=1
        return res

Java解法如下:

class Solution {
  public List<List<Integer>> threeSum(int[] nums) {
    List<List<Integer>> res = new ArrayList<>();
    Arrays.sort(nums);
    for (int i = 0; i + 2 < nums.length; i++) {
        if (i > 0 && nums[i] == nums[i - 1]) {              // skip same result
            continue;
        }
        int j = i + 1, k = nums.length - 1;  
        int target = -nums[i];
        while (j < k) {
            if (nums[j] + nums[k] == target) {
                res.add(Arrays.asList(nums[i], nums[j], nums[k]));
                j++;
                k--;
                while (j < k && nums[j] == nums[j - 1]) j++;  // skip same result
                while (j < k && nums[k] == nums[k + 1]) k--;  // skip same result
            } else if (nums[j] + nums[k] > target) {
                k--;
            } else {
                j++;
            }
        }
    }
    return res;
}
}

猜你喜欢

转载自blog.csdn.net/zhangpeterx/article/details/88719018