Tuesday, January 20, 2015

Leetcode 16: 3Sum Closest


Problem: 

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution. 

For example, given array S = {-1 2 1 -4}, and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

Analysis:
This problem is similar to 3Sum, instead we have to track the minimum gap during the process. The process of doing 3sum is the same:
Step 1: Sort the given array from low to high. 
Step 2: Get the sum of three different elements each time by using three pointers
           P1: traverse the array from the first element to the end-2. For each P1, another pointer P2                     points to the next element of P1 while the third pointer P3  points to the last element. 
Step 3: For each summation, keep tracking the minimum gap between the summation and the target,             and update the 

You may wonder why the three pointer algorithm achieves the minimum running time. The reason is that the first step make sure the each time, P1 points to a different value so that the combination of P1, P2 and P3 (P1<P2<P3) will never be traversed twice. Also,  you can consider this problem as a problem selecting three different elements from an array and then return the combinations.

public class Solution {
    public int threeSumClosest(int[] num, int target) {
        if(num==null || num.length<3){
            return -1;
        }
        int gap=Integer.MAX_VALUE;
        int temp=-1;
        Arrays.sort(num);
        for(int i=0;i<num.length;i++){
            int j=i+1;
            int k=num.length-1;
            while(j<k){
                int sum=num[i]+num[j]+num[k];
                if(Math.abs(target-sum)<gap){
                    gap=Math.abs(target-sum);
                    temp=sum;
                }
                if(sum<target){
                    j++;
                }else{
                    k--;
                }
            }
        }
        return temp;
    }
}


Thursday, January 1, 2015

Leetcode 15: 3 sum

Problem:
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)
Analysis:
The following solution is to first sort the array and then for each element, we continue to check the larger ones using two pointers and move them accordingly.

Also, as the array could contain duplicated elements, we need to find a way to filter out the same solution.

Code:
public class Solution {
    public List<List<Integer>> threeSum(int[] num) {
        List<List<Integer>> ret=new ArrayList<List<Integer>>();
        if(num==null||num.length<3){
            return ret;
        }
        Arrays.sort(num);
        Set<String> set=new HashSet<String>();
        for(int i=0;i<num.length;i++){
            int j=i+1;
            int k=num.length-1;
            while(j<k){
                if(num[i]+num[j]+num[k]==0){
                    set.add(tsort(num[i],num[j],num[k]));
                    j++;
                    k--;
                }else if(num[i]+num[j]+num[k]>0){
                    k--;
                }else{
                    j++;
                }
            }
        }
        for(String str:set){
            List<Integer> list=new ArrayList<Integer>();
            for(String val:str.split("_")){
                list.add(Integer.parseInt(val));
            }
            ret.add(list);
        }
        return ret;
    }
    private String tsort(int i,int j,int k){
        int min=Math.min(i,Math.min(j,k));
        int max=Math.max(i,Math.max(j,k));
        int mid=(i+j+k)-min-max;
        return min+"_"+mid+"_"+max;
    }
}

Leetcode 1: Two Sum

Problem:
Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

Analysis:
If we add two different elements in the array together and then compare each sum with the target, we will get a O(n^2) algorithm. However, if we change the expression A[i]+A[j]=target to A[j]=target-A[i],  our problem becomes search whether target-A[i] also exists in the array.

Code:

public class Solution {
    public int[] twoSum(int[] numbers, int target) {
        if(numbers==null || numbers.length<2){
            return null;
        }
        Map<Integer,Integer> map=new HashMap<Integer,Integer>(numbers.length);
        int ret[]=new int[2];
        for(int i=0;i<numbers.length;i++){map.put(numbers[i],i);}
        for(int i=0;i<numbers.length;i++){
            int val=target-numbers[i];
            if(map.containsKey(val) &&map.get(val)>i){
                ret[0]=i+1;
                ret[1]=map.get(val)+1;
                return ret;
            }
        }
        return null;
        
    }
}

Leetcode 128: Longest Consecutive Sequence

Problem:
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.

Your algorithm should run in O(n) complexity.

Analysis:
 The idea is to select one element first and then search larger consecutive ones and smaller ones. In this process, we need a map to record whether an integer exists or not and skip elements we have visited before.

Code:
public class Solution {
    public int longestConsecutive(int[] num) {
        Map<Integer,Boolean> map=new HashMap<Integer,Boolean>();
        for(int i=0;i<num.length;i++){
            map.put(num[i],true);
        }
        int maxLen=Integer.MIN_VALUE;
        for(int i=0;i<num.length;i++){
            if(map.get(num[i])){//not visited
                int val=num[i];
                int len=1;
                while(map.containsKey(--val)){
                    len++;
                    map.put(val,false);
                }
                val=num[i];
                while(map.containsKey(++val)){
                    len++;
                    map.put(val,false);
                }
                if(len>maxLen){
                    maxLen=len;
                }
            }
        }
        return maxLen;
    }
}