剑指offer 29. 数组中出现次数超过一半的数字
2017-05-05 16:46
501 查看
//题目:输入一个数组,输出出现次数大于总次数一半的数字 //解法1:输出数字的出现次数大于整体的一半,所以可以出现数字标记+1,不同数字-1,为0时更新数字并使标记为1 public class Main { public static void main(String[] args) throws Exception { System.out.println(getMaxNum(new int[]{2,2,2,3,3,3,2})); } public static int getMaxNum(int[] input){ int number = 0; int count = 0; for(int i = 0;i<input.length;i++){ if(count == 0){ number = input[i]; count = 1; continue; } if(number == input[i]){ count++; }else{ count--; } } return number; } } //解法2:使用快排思想,找到位置为mid的元素 public class Main { public static void main(String[] args) throws Exception { System.out.println(getMaxNum(new int[]{2,2,3,3,3,3,2})); } public static int getMaxNum(int[] input){ int low = 0; int high = input.length-1; int mid = (low+high)/2; int index = partition(input,low,high); while(index!=mid){ if(index<mid){ index = partition(input,index+1,high); }else{ index = partition(input,low,index-1); } } return input[index]; } public static int partition(int[] input,int low, int high){ int key = input[low]; while(low<high){ while(low<high && input[high]>=key){ high = high-1; } input[low] = input[high]; while(low<high && input[low]<=key){ low = low+1; } input[high] = input[low]; } input[low] = key; return low; } }
相关文章推荐
- [剑指offer][面试题29]数组中出现次数超过一半的数字
- 剑指offer-29数组中出现次数超过一半的数字
- 剑指Offer 29 数组中出现次数超过一半的数字
- 剑指offer-29:数组中出现次数超过一半的数字
- 算法题005 剑指Offer面试题29 数组中出现次数超过一半的数字
- 剑指offer 29题 【时间效率】数组中出现次数超过一半的数字
- 剑指Offer-29-数组出现次数超过一半的数字-基于Partition函数的O(n)算法
- 【剑指offer】5.2时间效率——面试题29:数组中出现次数超过一半的数字
- 【剑指Offer学习】【面试题29 :数组中出现次数超过一半的数字】
- 【剑指offer】Q29:数组中出现次数超过一半的数字
- 剑指offer 面试题29:数组中出现次数超过一半的数字及其变形(腾讯2015秋招 编程题4)
- 【剑指offer】面试题29:数组中出现次数超过一半的数字
- 剑指Offer:面试题29——数组中出现次数超过一半的数字(java实现)
- 剑指Offer----面试题29:数组中出现次数超过一半的数字
- 剑指offer面试题29-数组中出现次数超过一半的数字
- 剑指offer29题,牛客网中“数组中出现次数超过一半的数字”
- 剑指Offer面试题29数组中出现次数超过一半的数字(涉及快排)
- 剑指offer--面试题29:数组中出现次数超过一半的数字
- 剑指offer 面试题29—数组中出现次数超过一半的数字
- 剑指offer面试题29:数组中出现次数超过一半的数字