package leetcode;
public class offer_39 {
public int majorityElement(int[] nums) {
int target=nums[0];
int count=0;
//相同count就减一,不同则加一,因为target总存在,所以最后剩下的就是target
for(int i=0;i<nums.length;i++) {
if(count==0) {
target=nums[i];
count=count+1;
}
else {
if(target==nums[i]) {
count=count+1;
}else {
count=count-1;
}
}
}
return target;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
offer_39 off=new offer_39();
int[] nums= {1, 2, 3, 2, 2, 2, 5, 4, 2};
System.out.println(off.majorityElement(nums));
}
}