## [LintCode] Merge Intervals

public List<Interval> merge(List<Interval> intervals) { // write your code here List<Interval> res= new ArrayList<Interval>(); if(intervals.size() == 0 || intervals == null) return res; Collections.sort(intervals, new IntervalComparator()); Interval first = intervals.get(0); for(int i = 1; i < intervals.size(); i++) { Interval cur = intervals.get(i); if(cur.start <= first.end) { first.end = Math.max(cur.end, first.end); }else{ res.add(first); first = […]

## [LintCode] Best Time to Buy and Sell Stock II

public int maxProfit(int[] prices) { // write your code here int max = 0; for(int i = 1; i < prices.length; i++) { if(prices[i] – prices[i-1] > 0) max += prices[i] – prices[i-1]; } return max; }

## [LintCode] 3 Sum

public ArrayList<ArrayList<Integer>> threeSum(int[] numbers) { // write your code here ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); if(numbers.length == 0 || numbers == null) return res; Arrays.sort(numbers); for(int i = 0 ; i < numbers.length – 2; i++) { if(i != 0 && numbers[i] == numbers[i-1]) continue; int l = i+1; int r = numbers.length – 1; […]

## [LintCode] 3 Sum Closest

public int threeSumClosest(int[] numbers ,int target) { // write your code here Arrays.sort(numbers); if(numbers.length == 0 || numbers == null) return 0; int close = Integer.MAX_VALUE; for(int i = 0; i < numbers.length – 2; i++) { int j = i + 1; int k = numbers.length – 1; while(j < k) { int sum […]

## [LintCode] First Missing Positive

public int firstMissingPositive(int[] A) { // write your code here if(A == null || A.length == 0) return 1; int i = 0; int n = A.length; while(i < n) { if(A[i] >= 0 && A[i] < n && A[A[i]] != A[i]) swap(A, i, A[i]); else i++; } int k = 1; while(k < n […]

## [LintCode] Merge Sorted Array

public void mergeSortedArray(int[] A, int m, int[] B, int n) { // write your code here int i = m – 1; int j = n – 1; int index = m+n – 1; while(i >= 0 && j >= 0) { if(A[i] < B[j]) { A[index] = B[j]; j–; index –; } else{ A[index] […]

## [LintCode] Remove Duplicates from Sorted Array

public int removeDuplicates(int[] nums) { // write your code here int res = 0; if(nums.length == 0 || nums == null) return res; for(int i = 1 ; i < nums.length; i++) { if(nums[res] != nums[i]){ nums[++res] = nums[i]; } } return res+1; }

## [LintCode] Subarray Sum

public ArrayList<Integer> subarraySum(int[] nums) { // write your code here ArrayList<Integer> res = new ArrayList<Integer>(); if(nums.length == 0 || nums == null) return res; HashMap<Integer,Integer> map = new HashMap<Integer,Integer>(); int sum = 0; for(int i = 0 ; i < nums.length; i++) { sum += nums[i]; if(nums[i] == 0){ res.add(i); res.add(i); break; } if(sum == […]

## [LintCode] Remove Element

public int removeElement(int[] A, int elem) { // write your code here int res = 0; if(A.length == 0 || A == null) return res; for(int i = 0 ; i < A.length; i++) { if(A[i] != elem) A[res++] = A[i]; } return res; }