日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

15. 3Sum

發布時間:2025/7/14 41 豆豆
生活随笔 收集整理的這篇文章主要介紹了 15. 3Sum 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

一、題目

  1、審題

    

?

  2、分析:

    給出一個數字型數組,求任意三個數組中數字和為0的所有組合。

?

二、解答

  1、分析:

    a、將數組 nums 排序,遍歷數組中元素;

    b、遍歷下標為 i 的元素時,取 low 指針指向下標為 i + 1 的元素, high 指向數組最后一個元素下標;

    c、循環判斷 當 low < high 時,

      若? nums[i] + nums[low] + nums[high] = 0 , 則為一組符合的組合;  

        同時,low 和 high 繼續移動,若 nums[low] = nums[low+1],則 low++;

        若 nums[high] = nums[high -1] , 則 high--;

      若?nums[i] + nums[low] + nums[high] > 0, 則 high--;

      若?nums[i] + nums[low] + nums[high] < 0, 則 low++;

public class Solution {public List<List<Integer>> threeSum(int[] nums) {List<List<Integer>> list = new ArrayList<List<Integer>>();Arrays.sort(nums);int sum = 0;for(int i = 0; i < nums.length -2; i++) {

       if(nums[i] > 0) break;
if(i == 0 || (i > 0 && nums[i] != nums[i-1])) { // 第一個已經比過,排除相等的兩連續元素int low = i + 1;int high = nums.length - 1;sum = -nums[i];

          while(low < high) { // 拎出 nums[i], low 與high 相夾if(nums[low] + nums[high] == sum) {
              list.add(Arrays.asList(nums[i], nums[low], nums[high]));
while(low < high && nums[low] == nums[low + 1]) low++;while(low < high && nums[high] == nums[high - 1]) high--;low++;high--;} else if (nums[low] + nums[high] < sum) {low++;} else {high--;}}}}return list;} }

?

轉載于:https://www.cnblogs.com/skillking/p/9409352.html

總結

以上是生活随笔為你收集整理的15. 3Sum的全部內容,希望文章能夠幫你解決所遇到的問題。

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