Add to Array-Form of Integer
数组相加. 先把k变成数组格式, 然后想加. 最后再翻转数组.
数组相加. 先把k变成数组格式, 然后想加. 最后再翻转数组.
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 = […]
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; }
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; […]
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 […]
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 […]
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] […]
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; }
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 == […]
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; }