初始想法:
public static int majorityElement(int[] nums) {
int max = 0;
int result = nums[0];
for (int i = 0; i < nums.length - 1; i++) {
int count = 0;
for (int j = i + 1; j < nums.length; j++) {
if (nums[j] == nums[i]) {
count += 1;
}
}
result = count > max ? nums[i] : result;
max = count > max ? count : max;
}
System.out.println(result);
return result;
}
实现简单,但是耗时还费内存。
不用双重遍历会好很多。
优化后:
public static int majorityElement2(int[] nums) {
Arrays.sort(nums);
System.out.println(Arrays.toString(nums));
int max = 0;
int count = 1;
int result = nums[0];
for (int i = 0; i < nums.length - 1; i++) {
count = nums[i] == nums[i + 1] ? count + 1 : 1;
// System.out.println("count:"+count);
result = count > max ? nums[i] : result;
// System.out.println("result:"+result);
max = count > max ? count : max;
//System.out.println("max:"+max);
}
//System.out.println("Majority2:" + result);
return result;
}
优化后看到了一个题解:
学好数学真重要!!!
题目和最后题解来自Leetcode
https://leetcode-cn.com/problems/majority-element/