LeetCode算法入门- 3Sum -day9
生活随笔
收集整理的這篇文章主要介紹了
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則左移右指針。
代碼如下:
總結(jié)
以上是生活随笔為你收集整理的LeetCode算法入门- 3Sum -day9的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode算法入门- Compar
- 下一篇: 蓝桥杯大赛基础之--数列排序