1. Given an array of integers, find a contiguous subarray which has the largest sum.
hint:
Go through the array with 2 variable -- cur and count. cur is to mark the current major element.
When we might an element equals to cur, count++; else count--;
If count == 0, we remark cur as the next element.
1 class Sol { 2 boolean found; 3 int res; 4 } 5 public class Solution { 6 public int majorityElement(int[] num) { 7 Sol sol = helper(num, 0, num.length-1); 8 return sol.res; 9 } 10 public Sol helper(int[] num, int l, int r) { 11 Sol sol = new Sol(); 12 if (l == r) { 13 sol.found = true; 14 sol.res = num[l]; 15 return sol; 16 } 17 int mid = (r - l) / 2 + l; 18 boolean foundl = false, foundr = false; 19 Sol soll = helper(num, l, mid); 20 Sol solr = helper(num, mid+1, r); 21 if (soll.found && solr.found && soll.res == solr.res) { 22 sol.found = true; 23 sol.res = soll.res; 24 return sol; 25 } 26 int half = (r - l + 1) / 2; 27 if (soll.found && frequent(num, l, r, soll.res) > half) { 28 sol.found = true; 29 sol.res = soll.res; 30 return sol; 31 } 32 if (solr.found && frequent(num, l, r, solr.res) > half) { 33 sol.found = true; 34 sol.res = solr.res; 35 return sol; 36 } 37 else { 38 sol.found = false; 39 return sol; 40 } 41 } 42 public int frequent(int[] num, int left, int right, int target) { 43 int n = 0; 44 for (int i = left; i <= right; i++) { 45 if (num[i] == target) { 46 n++; 47 } 48 } 49 return n; 50 } 51 }
2. Given an array of integers and a number k, the majority number is the number that occurs more than 1/k
of the size of the array.
hint:
定义出现频率大于 1/k 的数为频繁项,这样的频繁项最多有 (k-1) 个。
1 public class MajorNumber { 2 public static void main(String[] args) { 3 MajorNumber mn = new MajorNumber(); 4 int[] A = {7,3,3,7,4,3,4,7,3,4,3,4,7,3,4}; // 3-6; 4-5; 7-4; 5 int m = 3; 6 mn.major(A, m); 7 } 8 9 public void major(int[] A, int m) { 10 HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); 11 int size = A.length / m; 12 System.out.println("size: "+size); 13 for (int i = 0; i < A.length; i++) { 14 if (map.containsKey(A[i])) { 15 int count = map.get(A[i]) + 1; 16 map.put(A[i], count); 17 } else { 18 map.put(A[i], 1); 19 if (map.size() >= m) { 20 List<Integer> list = new ArrayList<Integer>(); 21 for (Integer key : map.keySet()) { 22 int count = map.get(key) - 1; 23 if (count == 0) { 24 list.add(key); 25 } 26 map.put(key, count); 27 } 28 for (Integer key : list) { 29 map.remove(key); 30 } 31 } 32 } 33 } 34 ArrayList<Integer> list = new ArrayList<Integer>(); 35 for (Integer key : map.keySet()) { 36 map.put(key, 0); 37 } 38 for (int i = 0; i < A.length; i++) { 39 if (map.containsKey(A[i])) { 40 int count = map.get(A[i]) + 1; 41 map.put(A[i], count); 42 } 43 } 44 45 for (Integer key : map.keySet()) { 46 if (map.get(key) > size) { 47 System.out.println(key); 48 } 49 } 50 return; 51 } 52 }