LeetCode 169. Majority Element
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋
times.
You may assume that the array is non-empty and the majority element always exist in the array.
思路1:
用map记录元素对应的次数,当次数大于数组大小的一半时,返回该数字。
代码1:
1 public static int majorityElement(int[] nums) { 2 Integer times; 3 Map<Integer, Integer> map = new HashMap<>(); 4 for(int n : nums){ 5 times = map.put(n, 1); 6 if(times != null){ 7 map.put(n, times+1); 8 if((times+1) > nums.length/2){ 9 return n; 10 } 11 } 12 } 13 return nums[0]; 14 }
思路2:
用一个标记cnt记录某个元素出现的次数,如果后面的元素和它相同就加一,有一个元素和他不相同就减一,当cnt小于等于0时重新记录新的元素。
代码2:
1 public static int m(int[] num) { 2 int main = num[0]; // 用于记录主元素,假设第一个是主元素 3 int count = 1; // 用于抵消数的个数 4 for (int i = 1; i < num.length; i++) { // 从第二个元素开始到最后一个元素 5 if (main == num[i]) { // 如果两个数相同就不能抵消 6 count++; // 用于抵消的数据加1 7 } else { 8 if (count > 0) { // 如果不相同,并且有可以抵消的数 9 count--; // 进行数据抵消 10 } else { // 如果不相同,并且没有可以抵消的数 11 main = num[i]; // 记录最后不可以抵消的数 12 } 13 } 14 } 15 return main; 16 }
There is no holding back time you said .
So you run your race ,made your transformation and left your mark .