温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

leetcode 137 && 360一面算法 &&有道一面

发布时间:2020-04-21 01:07:46 来源:网络 阅读:671 作者:努力的C 栏目:建站服务器

题目描述:给一个数组,有一个数出现了两次或者1次,而其他数都出现了三次,找出这个数。其实对应了leetcode 137。


网上的解法多是位运算

public int singleNumber(int[] nums) {    
int ans = 0;   
 for(int i = 0; i < 32; i++) {      
  int sum = 0;        
  for(int j = 0; j < nums.length; j++) {         
    if(((nums[j] >> i) & 1) == 1) {
                sum++;
                sum %= 3;
            }
        }      
          if(sum == 1) {
            ans |= sum << i;
        }        
        if(sum == 2) {
            ans |= sum/2 << i
        }
    }    return ans;
}

利用位运算,求每位1出现的次数,出现3次的最后加起来%3==0. !=0的要么是1次,要么是2次。分情况讨论就行。最后的| 或运算,很强哦。。。




有道给的是一个数出现了一次,其他数都出现了三次,找出这一个数,对应LeetCode137题!位运算

class Solution {
    public int singleNumber(int[] nums) {
       int length = nums.length;  
        int result = 0;  
        for(int i = 0; i<32; i++){  
            //int count = 0;   
            int temp = 0;  
            for(int j=0; j<length; j++){  
                temp+=(nums[j]>>i & 1);
                    //count++;  
            }  
          //if(count %3==1)  
                result |= (temp%3)<<i;  
        }  
        return result; 
    }
}

当时写的时候出现了一点小小的问题,就是最后 | 的时候,忘记左移回来了。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI