Leetcode_169_Majority Element
来源:互联网 发布:淘宝卖家模板 编辑:程序博客网 时间:2024/05/12 19:50
本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/42247887
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋
times.
You may assume that the array is non-empty and the majority element always exist in the array.
思路:
(1)题意为给定一个整形数组,寻找出现次数大于数组长度一半的数字。
(2)这道题很简单。如果你对Arrays类比较熟悉的话,可以先运用其中的sort()方法对数组排序,排完序后再从左到右遍历遍历数组,并设置count记录遍历数字出现的次数,如果大于数组长度一半则返回。
(3)这道题如果不用上述方法,可以只遍历一次就得到结果,这里不再啰嗦了,详见下方代码。
(4)希望本文对你有所帮助。
算法代码实现如下:
public static int majorityElement(int[] num) {if(num==null ||num.length==0) return-1;if(num!=null &&num.length==1) return num[0];Arrays.sort(num);int count = 1;int flag = 0;for (int i = flag+1; i < num.length; i++) {if(num[flag]==num[i]){count++;if(count>num.length/2){return num[flag];}}else{flag=i;count=1;}}return -1;}
只遍历一次算法的代码实现如下:
public static int majorityElement(int[] num) {if (num == null || num.length == 0)return -1;int count = 0;int index = 0;for (int i = 0; i < num.length; ++i) {if (index == 0)count = num[i];if (count == num[i])++index;else--index;}return count;}
0 0
- Leetcode_169_Majority Element
- leetcode_169_Majority Element
- leetcode_169_Majority Element(C++)(easy)
- Element
- Element
- element
- element jquery
- element.childNodes
- dom element
- expat:element
- Element Object
- Element 对象
- prototype Element
- Remove Element
- Remove Element
- Remove Element
- Remove Element
- Remove Element
- 黑马程序员-String字符串练习
- UML7.5快捷键大全
- OC 多态理解
- teqc: currently cannot deal with an applied clock offset in QC mode
- 字符数组 与 字符指针(使用前分配内存)
- Leetcode_169_Majority Element
- 将spring的bean配置文件分模块定义
- linux驱动虚拟地址和物理地址的映射
- hdu1008
- Vim配置及说明 IDE编程环境
- pycurl: libcurl link-time ssl backend (nss) is different from compile-time ssl backend (none/other)
- 虚拟地址到物理地址的映射
- http状态码/http返回码详解
- Spring与JMX集成