public class Solution {
public int majorityElement(int[] nums) {
HashMap<Integer, Integer> elementNum = new HashMap(nums.length/2);
for (int element : nums) {
if (elementNum.containsKey(element)) {
elementNum.put(element, elementNum.get(element)+1);
}
else {
elementNum.put(element, 1);
}
}
Set<Map.Entry<Integer, Integer>> set = elementNum.entrySet();
Iterator<Map.Entry<Integer, Integer>> iter = set.iterator();
while (iter.hasNext()) {
Map.Entry<java.lang.Integer, java.lang.Integer> entry = (Map.Entry<java.lang.Integer, java.lang.Integer>) iter
.next();
if (entry.getValue()>nums.length/2) {
return entry.getKey();
}
}
return 0;
}
}
解法二:
public class Solution {
public int majorityElement(int[] nums) {
if (nums.length == 1) {
return nums[0];
}
int[][] keyValue = new int[nums.length][2];
int sumDiffNum = 0,stus = 0;
for (int i = 0; i < nums.length; i++) {
stus = 0;
for (int j = 0; j < sumDiffNum+1; j++) {
if (nums[i]==keyValue[j][0]) {
keyValue[j][1]++;
stus = 1;
break;
}
}
if (stus == 0) {
keyValue[sumDiffNum][0] = nums[i];
keyValue[sumDiffNum][1] = 1;
sumDiffNum++;
stus = 0;
}
}
for (int i = 0; i < sumDiffNum+1; i++) {
if (keyValue[i][1]>nums.length/2) {
return keyValue[i][0];
}
}
return nums[0];
}
}