标签:空间复杂度 span 变量 key hal 遍历 pre div more
import java.util.HashMap; public class Solution { public int MoreThanHalfNum_Solution(int [] array) { HashMap<Integer, Integer> map = new HashMap<>(); if (array.length == 1) return array[0]; for (int i = 0; i < array.length; i++) { if (map.containsKey(array[i])) { int count = map.get(array[i]); if (count >= array.length / 2) return array[i]; map.put(array[i], count + 1); } else { map.put(array[i], 1); } } return 0; } }
public class Solution { public int MoreThanHalfNum_Solution(int [] array) { if (array.length == 0) return 0; if (array.length == 1) return array[0]; int left = 0; int right = array.length - 1; while (left < right) { int index = position(array, left, right); if (index == array.length / 2) { if (checkMoreThanHalf(array, array[index])) return array[index]; else return 0; } else if (index < array.length / 2) left = index + 1; else right = index - 1; } return 0; } private int position(int[] array, int start, int end) { int index = start + (int)Math.random() * (end - start); swap(array, index, end); int small = start - 1; for (int i = start; i < end; i++) { if (array[i] <= array[end] && ++small != i) { swap(array, small, i); } } swap(array, ++small, end); return small; } private void swap(int[] array, int a, int b) { int temp = array[a]; array[a] = array[b]; array[b] = temp; }
//验证数组是否合理 private boolean checkMoreThanHalf (int[] array, int result) { int times = 0; for (int i = 0; i < array.length; i++) { if (array[i] == result) times++; } if (times * 2 <= array.length) return false; else return true; } }
public class Solution { public int MoreThanHalfNum_Solution(int [] array) { int len = array.length; if (len == 0) return 0; if (len == 1) return array[0]; int result = array[0]; int times = 1; for (int i = 1; i < len; i++) { if (times == 0) { result = array[i]; times = 1; } else if (array[i] == result) { times++; } else { times--; } } if (times >= 1 && checkMoreThanHalf(array, result)) return result; else return 0; } private boolean checkMoreThanHalf (int[] array, int result) { int times = 0; for (int i = 0; i < array.length; i++) { if (array[i] == result) times++; } if (times * 2 <= array.length) return false; else return true; } }
标签:空间复杂度 span 变量 key hal 遍历 pre div more
原文地址:https://www.cnblogs.com/weiququ/p/12387259.html