Leetcode15. 3Sum

Leetcode15. 3Sum

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]
]

解法

  • 首先对数组进行排序,排序后固定一个数nums[i],再使用左右指针指向nums[i]后面的两端,数字分别为nums[L]nums[R],计算三个数的和 sum 判断是否满足为 0,满足则添加进结果集
  • 如果nums[i]大于 0,则三数之和必然无法等于0,结束循环
  • 如果nums[i] == nums[i−1],则说明该数字重复,会导致结果重复,所以应该跳过
  • 当 sum == 0 时,nums[L] == nums[L+1] 则会导致结果重复,应该跳过,L++
  • 当 sum == 0 时,nums[R] == nums[R−1] 则会导致结果重复,应该跳过,R--

Java

class Solution {
    public static List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> ans = new ArrayList();
        int len = nums.length;
        if(nums == null || len < 3) return ans;
        Arrays.sort(nums); // 排序,时间复杂度O(nlogn)
        for (int i = 0; i < len ; i++) {
            if(nums[i] > 0) break; // 如果当前数字大于0,则三数之和一定大于0,所以结束循环
            //下一步我写错成 if(nums[i] == nums[i+1]) continue;
            if(i > 0 && nums[i] == nums[i-1]) continue; // 去重
            int L = i + 1;
            int R = len-1;
            while(L < R){
                int sum = nums[i] + nums[L] + nums[R];
                if(sum == 0){
                	//Arrays的asList()方法可以将数组转为List但是,这个数组类型必须是引用类型的
                    ans.add(Arrays.asList(nums[i],nums[L],nums[R]));
                    while (L<R && nums[L] == nums[L+1]) L++; // 去重
                    while (L<R && nums[R] == nums[R-1]) R--; // 去重
                    L++;
                    R--;
                }
                else if (sum < 0) L++;
                else if (sum > 0) R--;
            }
        }        
        return ans;
    }
}
  • 时间复杂度: O ( N 2 ) O(N^2) :数组排序 O ( n l o g n ) O(nlogn) ,遍历数组O(N),双指针遍历O(N)。
  • 空间复杂度:O(1)。

Python

class Solution(object):
	def threeSum(self, nums):
		res = []
		nums.sort()
		length = len(nums)
		for i in range(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]: #[6]
						l+=1
					while l<r and nums[r]==nums[r-1]: #[6]
						r-=1
					l+=1
					r-=1
		return res

C++

vector<vector<int> > threeSum(vector<int> &num) {    
    vector<vector<int> > res;
    std::sort(num.begin(), num.end());
    for (int i = 0; i < num.size(); i++) {       
        int target = -num[i];
        int front = i + 1;
        int back = num.size() - 1;
        
        while (front < back) {
            int sum = num[front] + num[back];          
            // Finding answer which start from number num[i]
            if (sum < target)
                front++;
            else if (sum > target)
                back--;
            else {
                vector<int> triplet(3, 0);
                triplet[0] = num[i];
                triplet[1] = num[front];
                triplet[2] = num[back];
                res.push_back(triplet);               
                // Processing duplicates of Number 2
                // Rolling the front pointer to the next different number forwards
                while (front < back && num[front] == triplet[1]) front++;
                // Processing duplicates of Number 3
                // Rolling the back pointer to the next different number backwards
                while (front < back && num[back] == triplet[2]) rear--;
            }         
        }
        // Processing duplicates of Number 1
        while (i + 1 < num.size() && num[i + 1] == num[i]) 
            i++;
    }
    
    return res;
    
}
发布了54 篇原创文章 · 获赞 3 · 访问量 3670

猜你喜欢

转载自blog.csdn.net/magic_jiayu/article/details/104060597