参考了别人的想法,思路简洁,效率高。虽然是在充分理解别人的思路后写出的代码,但是还是发现了自己的不足之处。以后还是要多思考多写。加油吧!

 

 

public class Solution {
    public int majorityElement(int[] num) {
        
        int ans = 0, cnt = 0;
         for(int i=0; i<num.length; i++) {
             if(cnt == 0) {
                 ans = num[i];
                 cnt ++;
             } else {
                 if(ans == num[i]) {
                     cnt ++;
                 } else {
                     cnt --;
                 }
              }
         }
         
         return ans;
        
    }
}

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-09-25
  • 2021-07-07
  • 2021-05-29
  • 2021-08-13
  • 2022-01-02
猜你喜欢
  • 2021-09-21
  • 2021-07-25
  • 2021-10-18
  • 2021-06-19
  • 2022-01-23
  • 2022-12-23
相关资源
相似解决方案