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

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

LeetCode算法入门- 3Sum -day9

發(fā)布時(shí)間:2025/3/12 编程问答 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 LeetCode算法入门- 3Sum -day9 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

LeetCode算法入門- 3Sum -day9

  • 題目描述:
    Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
  • Note:

    The solution set must not contain duplicate triplets.

    Example:

    Given array nums = [-1, 0, 1, 2, -1, -4],
    A solution set is:
    [
    [-1, 0, 1],
    [-1, -1, 2]
    ]

  • 思路分析:
    題目的意思是找到數(shù)組中所有3個(gè)和為0的數(shù),并且不能重復(fù)。
  • 該題可以轉(zhuǎn)化成Two Sum的思路去解決先固定一個(gè)數(shù),然后從數(shù)組中剩下的數(shù)中查找和為該數(shù)負(fù)值(target)得2個(gè)數(shù),則轉(zhuǎn)化成了Two Sum問題:1. 先排序數(shù)組,使兩個(gè)指針分別指向首尾的兩個(gè)數(shù),2. 如果這兩個(gè)數(shù)和等于target,則找到,3. 如果小于target則右移左指針,如果大于target則左移右指針。

  • 關(guān)鍵是題目要求去重,所以每次移動(dòng)指針的時(shí)候要判斷一下是否和上一個(gè)數(shù)相同,如果相同則繼續(xù)移動(dòng)。
    代碼如下:
  • class Solution {public List<List<Integer>> threeSum(int[] nums) {int len = nums.length;List<List<Integer>> result = new ArrayList<>();//記得先排序,這樣才能夠排除重復(fù)的答案Arrays.sort(nums);for(int i = 0; i < len; i++){//這里的i != 0的判斷目的是為了i-1不越界if(i != 0 && nums[i] == nums[i - 1])//continue語法很少用,若條件滿足,則不執(zhí)行當(dāng)次循環(huán)的代碼,i要繼續(xù)+1continue;int target = -nums[i];int left = i + 1;int right = len - 1;while(left < right){if(nums[left] + nums[right] == target){//Arrays.asList()這個(gè)方法是直接將元素添加到temp中去List<Integer> temp = Arrays.asList(nums[i],nums[left],nums[right]);result.add(temp);left++;right--;//去重同時(shí)記得判斷l(xiāng)eft<rightwhile(left < right && nums[left] == nums[left-1])left++;while(left < right && nums[right] == nums[right+1])right--;}else if(nums[left] + nums[right] < target){left++;}else{right--;}}}return result;} }

    總結(jié)

    以上是生活随笔為你收集整理的LeetCode算法入门- 3Sum -day9的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。