[LeetCode][JavaScript]3Sum

來源:互聯網
上載者:User

標籤:

3Sum

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

Note:

  • Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
  • The solution set must not contain duplicate triplets.
    For example, given array S = {-1 0 1 2 -1 -4},    A solution set is:    (-1, 0, 1)    (-1, -1, 2)

https://leetcode.com/problems/3sum/

 

 

 

 

 

一開始就想到暴力三重迴圈,提示說雙指標。

先要排序,這題的解法很依賴順序。

外層迴圈從頭到尾,內層用雙指標。

內層每一輪將兩指標指向的值和外層迴圈的值相加,如果相等說明找到了;如果小於0,頭指標往後走;大於0尾指標往前。可以這樣做就是基於已經排過序了。

 1 /** 2  * @param {number[]} nums 3  * @return {number[][]} 4  */ 5 var threeSum = function(nums) { 6     var res = []; 7     nums = nums.sort(sorting); 8  9     for(var i = 0; i < nums.length - 2; i++){10         if(nums[i - 1] !== undefined && nums[i - 1] === nums[i]){11             continue;12         }13         var curr = nums[i];14         var m = i + 1;15         var n = nums.length - 1;16         while(m < n){17             if(nums[m] + nums[n] + curr === 0){18                 res.push([curr, nums[m], nums[n]]);19                 while(m < n && nums[m] === nums[m + 1]){20                     m++;21                 }22                 while(m < n && nums[n] === nums[n - 1]){23                     n--;24                 }25                 m++; n--; 26             } else if(nums[m] + nums[n] + curr > 0){27                 n--;28             } else {29                 m++;30             }31         }32     }33     return res;34 35     function sorting(a, b){36         if(a > b){37             return 1;38         }else if(a < b){39             return -1;40         }else{41             return 0;42         }43     }44 };

 

 

[LeetCode][JavaScript]3Sum

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.