当前位置:网站首页>Leetcode topic [array] -18- sum of four numbers

Leetcode topic [array] -18- sum of four numbers

2022-06-25 22:02:00 LabRat

Force link :https://leetcode-cn.com/probl...
Their thinking :

  1. I have tried many ways to brush questions before , On the one hand, I feel that my technical accumulation and understanding and application of language are really poor , On the other hand, the idea of writing questions is wrong , It has its defects to brush according to the order of questions or simply according to the difficulty , First, brush in the order of topics , In fact, the knowledge points of each subject are different , Dongyi hammer , West a mallet , It is difficult to systematically learn a certain knowledge point , Play according to the difficulty , From the beginning mid perhaps hard The subject of , It will soon reduce the efficiency of writing questions because of the fear of difficulties . This time a new method has been adopted , First of all, there are categories , Such as arrays / Linked list / Trees / Dynamic planning, etc , Then each category begins with a simple question , Brush each category and each difficulty 20 Problem . After a period of verification , It's a double effect
  2. Back to the problem itself , Sum of three numbers / The closest sum of three / Sum of four numbers , In essence, they all adopt one method , That's sort + Double pointer , The last two digits must be double pointers , Then the remaining numbers need to be iterated
  3. This problem is to optimize an unnecessary convenience , Some optimization has been done to the boundary , Of course, these are small optimizations , Algorithms that do not change nature
func fourSum(nums []int, target int) [][]int {
    n := len(nums)
    sort.Ints(nums)
    ans := make([][]int, 0)
    for i := 0; i < n-3 && nums[i]+nums[i+1]+nums[i+2]+nums[i+3] <= target; i++ {
        if i > 0 && nums[i] == nums[i-1] || nums[i]+nums[n-1]+nums[n-2]+nums[n-3] < target {
            continue
        }
        for j := i + 1; j < n-2 && nums[i]+nums[j]+nums[j+1]+nums[j+2] <= target; j++ {
            if j > i+1 && nums[j] == nums[j-1] || nums[i]+nums[j]+nums[n-1]+nums[n-2] < target {
                continue
            }
            k, l := j+1, n-1
            for k < l {
                sum := nums[i] + nums[j] + nums[k] + nums[l]
                if sum == target {
                    ans = append(ans, []int{nums[i], nums[j], nums[k], nums[l]})
                    for k++; k < l && nums[k] == nums[k-1]; k++ {
                    }
                    for l--; k < l && nums[l] == nums[l+1]; l-- {
                    }
                } else if sum > target {
                    l--
                } else {
                    k++
                }
            }
        }
    }
    return ans
}
原网站

版权声明
本文为[LabRat]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202181138474730.html