leetcode15. Sum of three numbers

The main idea of ​​the title: Find the triplet with the sum of three elements in the set equal to 0 and no repetition

Topic analysis: This question directly uses brute force search to enumerate all situations, the time complexity is O(n^3), and the timeout

The second method is used below, and the time complexity is reduced to O(n^2): its idea is to first sort the elements in the set from small to large, and then determine that the first element in the triple is the first element in the set an element, and then use the pointers j, k to point to the second element and the last element respectively. If i+j+k=0 at this time, it means that it is a condition that meets the conditions. If i+j+k>0, it means that the current sum is too large, so k should be moved forward. If you move j backward, the result will be bigger. If i+j+k<0, it means that the current sum is too small, move j backwards. When i and j meet, the situation has been traversed. Then take the second element in the set as the first element in the triplet, j points to the third element in the set, k points to the last element, similar comparison..., before each case is added, determine whether it is repeated .

After doing this, it was found that it still timed out. The reason lies in the judgment repeating this step. We can simplify by a few steps. If nums[i] = nums[i-1], then the two numbers obtained after that are combined with nums[i], and the two numbers obtained after that are combined with nums[i-1]. This situation is repeated. Also, when j is moved backward and k is moved forward, if the two numbers before and after (such as nums[j], nums[j+1]) are equal, duplication will also occur in this case.

Code display:

class Solution:
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        result = []
        nums.sort()
        for i in range(len(nums)-2):
            if i>0 and nums[i]==nums[i-1]:
                continue
            j = i+1
            k = len (nums) -1
            while j<k:
                temp = nums[i]+nums[j]+nums[k]
                if temp>0:
                    k = k-1
                elif temp<0:
                    d = d+1
                else:
                    result.append([nums[i],nums[j],nums[k]])
                    while j<k and nums[j]==nums[j+1]:
                        d = d+1
                    while j<k and nums[k]==nums[k-1]:
                        k = k-1     
                    d = d+1
                    k = k-1
        return result

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326166379&siteId=291194637