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] ] Solution 1:
public class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> returnList = new ArrayList<List<Integer>>();
if(nums==null||nums.length < 2) return returnList;
Arrays.sort(nums);
int length = nums.length;
for(int i=0;i<length;i++){
if(i>0 && nums[i]==nums[i-1]) continue;
int j=i+1;
int k=length-1;
int target = 0 - nums[i];
while(j<k){
if(nums[j]+nums[k] == target){
returnList.add(Arrays.asList(nums[i], nums[j], nums[k]));
while(j<k && nums[j]==nums[j+1]) j++;
while(j<k && nums[k]==nums[k-1]) k--;
j++;k--;
}else if(nums[j]+nums[k] < target){
j++;
}else{
k--;
}
}
}
return returnList;
}
} Question : Given an array of integers A, return the largest integer that only occurs once.…
Jump search algorithm is a pretty new algorithm to search for an element in a…
What is Knuth Morris Pratt or KMP algorithm ? KMP is an algorithm which is…
Binary Search is a Logarithmic search which finds the target element in a sorted array…
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol Value I 1 V 5 X…
Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such…
This website uses cookies.