import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class test19 {
/**
* 给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数 大于n/2的元素。
* 你可以假设数组是非空的,并且给定的数组总是存在多数元素。
*
* 示例1:
* 输入:[3,2,3]
* 输出:3
*
* 示例2:
* 输入:[2,2,1,1,1,2,2]
* 输出:2
*
* 进阶:
* 尝试设计时间复杂度为 O(n)、空间复杂度为 O(1) 的算法解决此问题。
*
* @param args
*/
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] str = br.readLine().split(",");
int[] nums = new int[str.length];
for(int i=0; i< str.length; i++){
nums[i] = Integer.parseInt(str[i]);
}
System.out.println(majorityElement(nums));
}
public static int majorityElement(int[] nums){
int count = 0;
Integer c = null;
for(int num: nums){
if(count == 0){
c = num;
}
count += (num == c) ? 1 : -1;
}
return c;
}
}
06-16
657
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交