solution1 : 有序数组的一半肯定是众数
class Solution {
public int removeDuplicates(int[] nums) {
int len = nums.length;
int slow= 2, fast = 2;
if(len <= 2){
return len;
}
while(fast<len){
if(nums[slow - 2]!=nums[fast]){
nums[slow] = nums[fast];
++slow;
}
++fast;
}
return slow;
}
}
solution2 : hashmap(回顾下代码)
class Solution {
private Map<Integer, Integer> countNums(int[] nums) {
Map<Integer, Integer> counts = new HashMap<Integer, Integer>();
for (int num : nums) {
if (!counts.containsKey(num)) {
counts.put(num, 1);
} else {
counts.put(num, counts.get(num) + 1);
}
}
return counts;
}
public int majorityElement(int[] nums) {
Map<Integer, Integer> counts = countNums(nums);
Map.Entry<Integer, Integer> majorityEntry = null;
for (Map.Entry<Integer, Integer> entry : counts.entrySet()) {
if (majorityEntry == null || entry.getValue() > majorityEntry.getValue()) {
majorityEntry = entry;
}
}
return majorityEntry.getKey();
}
}
solution3 : 用正负判断数的个数,如77555,假设第一个数是7,则(7,1) -> (7,2) -> (7,1) -> (7,0) -> (5, 1)
class Solution {
public int majorityElement(int[] nums) {
int count = 0;
Integer candidate = null;
for (int num : nums) {
if (count == 0) {
candidate = num;
}
count += (num == candidate) ? 1 : -1;
}
return candidate;
}
}