日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

LeetCode 三数之和 — 优化解法

發布時間:2023/12/10 编程问答 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 LeetCode 三数之和 — 优化解法 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

LeetCode 三數之和 — 改進解法

題目:給定一個包含 n 個整數的數組 nums,判斷 nums 中是否存在三個元素 a,b,c ,使得 a + b + c = 0 ?找出所有滿足條件且不重復的三元組。
注意:答案中不可以包含重復的三元組。
例如, 給定數組 nums = [-1, 0, 1, 2, -1, -4],
滿足要求的三元組集合為:
[ [-1, 0, 1], [-1, -1, 2] ]

 最開始做的解法是先將整個數組排序;然后遍歷前兩個數(a和b)的所有情況(n^2);對于第三個數,則從剩余的數中(即從第二個數下一個位置開始到末尾)利用二分查找出是否存在數字 -(a+b)即可。 復雜度O(n^2·logn) :

class Solution {public List<List<Integer>> threeSum(int[] nums) {List<List<Integer>> ans = new ArrayList<List<Integer>>();Arrays.sort(nums);Map<Integer,Integer> mi = new HashMap();for(int i=0;i<nums.length-1;i++) {if(mi.get(nums[i]) != null) continue; //記錄i下標讀過的數字mi.put(nums[i],1);Map<Integer,Integer> mj = new HashMap(); for(int j=i+1;j<nums.length;j++) {if(mj.get(nums[j]) != null) continue; //記錄j下標讀過的數字mj.put(nums[j],1);int temp = -(nums[i]+nums[j]);if(bSearch(nums,j+1,nums.length-1,temp) == false) continue; //二分搜索j下標之后的區間是否有數字tempans.add(Arrays.asList(nums[i],nums[j],temp));}}return ans;}//二分算法public boolean bSearch(int[] nums,int s,int e,int key) {int start=s,end=e,mid;while(start<=end){mid = (start+end)/2;if(key < nums[mid]) end=mid-1;else if(key > nums[mid]) start=mid+1;else if(key == nums[mid]) return true;}return false;} }

里面有兩個用了哈希的地方,所以時間復雜度應該還要乘上一個常數K...(解數組相關的題感覺總有些依賴哈希的方法=_= ...)




 最近做了另一個數組區間相關的題目,受其解法的啟發,打算對這道題解法進行優化。
 還是先對數組進行排序;對第一個數字(a)進行遍歷,而然后在剩余的數中用前后指針的方法找出兩個和為-a的數字:兩個指針left和right;left初始化為數字a的下一位置,right為最后一個位置。比較nums[left]+nums[right]+a和0的大小;如果大于0則right--,小于就left++。 其中在添加結果集時需考慮去重問題,用個哈希判斷是否有重復就行了,復雜度O(n^2·K) :

class Solution {public List<List<Integer>> threeSum(int[] nums) {List<List<Integer>> ans = new ArrayList<List<Integer>>();Arrays.sort(nums);Map<Integer,Integer> mi = new HashMap();for(int i=0;i<nums.length-2;i++) {if(mi.get(nums[i]) != null) continue; //記錄i下標讀過的數字mi.put(nums[i],1);Map<Integer,Integer> mj = new HashMap();int l = i+1, r = nums.length-1, temp;while(l<r) {temp = nums[i] + nums[l] + nums[r];if(temp < 0) {l++;} else if(temp > 0) {r--;} else {if((mj.get(nums[l])) == null) {ans.add(Arrays.asList(nums[i], nums[l], nums[r]));mj.put(nums[l], 1);}l++; r--;}}}return ans;} }

轉載于:https://www.cnblogs.com/geek1116/p/10172313.html

總結

以上是生活随笔為你收集整理的LeetCode 三数之和 — 优化解法的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。