原题链接:https://leetcode.com/problems/majority-element/description/
这道题目之前《剑指Offer》见到过,这次就直接能想起书上写的第二种较为简单的方法了:
/**
* Created by clearbug on 2018/2/26.
*/
public class Solution {
public static void main(String[] args) {
Solution s = new Solution();
System.out.println(s.majorityElement(new int[]{1, 2, 2, 3, 2, 5}));
System.out.println(s.majorityElement(new int[]{1, 2, 2, 3, 2, 5, 8, 8, 8, 7, 6, 5, 8}));
}
public int majorityElement(int[] nums) {
int times = 1;
int temp = nums[0];
for (int i = 1; i < nums.length; i++) {
if (nums[i] == temp) {
times++;
} else {
if (times > 0) {
times--;
} else {
temp = nums[i];
times = 1;
}
}
}
return temp;
}
}
第一种方法,就是利用快速排序的思想来解决啦!