当前位置:网站首页>Sword finger offer 56 - I. number of occurrences in the array

Sword finger offer 56 - I. number of occurrences in the array

2022-06-13 04:26:00 GRT has to keep working hard

 Insert picture description here First review , If all but one number , The other numbers appear twice , So how to find the number that appears once ? The idea is to make the array elements different or .

 Insert picture description here

class Solution {
    
    public int[] singleNumbers(int[] nums) {
    
       int z = 0;
       for(int num:nums){
    
           z^=num;// To obtain the z For two different numbers x And y The result of exclusive or .  According to the nature of XOR ,z At least one of them is 1、 Next, find out this bit .
       }
       int m = 1;
       while((z&m) == 0){
    m<<=1;}
       int x = 0,y = 0;
       for(int i:nums){
    
           if((i&m) == 0){
    x^=i;}
           else {
    y^=i;}
       }
       return new int[]{
    x,y};
    }
}

Answer key

原网站

版权声明
本文为[GRT has to keep working hard]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/164/202206130419073618.html