leet_15
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leet_15相关的知识,希望对你有一定的参考价值。
Given an array S of n integers, are there elements a, b, c 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)
package com.mingxin.leetcode.leet_15; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Created by Administrator on 2016/1/25. */ public class ThreeSum { public static void main(String[] args){ int num[] = {-1, -20, -5, -7, 0, 1, 2, 7, 6, 10}; List<List<Integer>> result = threeSum(num); for(List<Integer> item1:result){ System.out.println("{" + item1.get(0) + ", " + item1.get(1) + ", " + item1.get(2) + "}"); } } public static List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> res = new ArrayList<List<Integer>>(); if(nums.length<3||nums == null){ return new ArrayList<List<Integer>>(); } Arrays.sort(nums); for(int i = 0; i <= nums.length-3; i++){ if(i==0||nums[i]!=nums[i-1]){ int low = i+1; int high = nums.length-1; while(low<high){ int sum = nums[i]+nums[low]+nums[high]; if(sum == 0){ ArrayList<Integer> unit = new ArrayList<Integer>(); unit.add(nums[i]); unit.add(nums[low]); unit.add(nums[high]); res.add(unit); low++; high--; while(low<high&&nums[low]==nums[low-1]){ low++; } while(low<high&&nums[high]==nums[high+1]){ high--; } }else if(sum > 0){ high --; } else{ low ++; } } } } return res; } }
以上是关于leet_15的主要内容,如果未能解决你的问题,请参考以下文章
Atom编辑器折腾记_(15)JS代码片段补全(插件:javascript-snippets)
Leet code problem 7: reverse integer digit
Leet Code OJ 102. Binary Tree Level Order Traversal [Difficulty: Easy]