leetcode 136. Single Number

来源:互联网 发布:恩比德 知乎 编辑:程序博客网 时间:2024/06/08 08:21

104. Maximum Depth of Binary Tree


Given two strings s and t which consist of only lowercase letters.

String t is generated by random shuffling string s and then add one more letter at a random position.

Find the letter that was added in t.

Example:

Input:s = "abcd"t = "abcde"Output:eExplanation:'e' is the letter that was added.

分析:相同元素的偶数次异或,总是得到0,0和其他元素异或得到这个元素本身。这个题目还有很多变身,文后会一一列举说明。


public class Solution {
    public int singleNumber(int[] nums) {
        int result = 0;
        for(int i=0;i<nums.length;i++){
            result = result^nums[i];
        }
        return result;
    }
}


通用性解法:上述的情况只适用于其他元素出现偶数次的情况,但是出现奇数次的话,上面的方法将不再适用。不妨设,其他元素出现了N次,那么这些元素相对应的二进制数的相同位置的和能被N整除。比如{1,1,1,2,2,2}各元素出现了三次。1的二进制01,2的二进制10。三个01,对应位置的和能被三整除,同理10也是如此。如果某个位置上的和不能被三整除,说明单个元素的位置一定在这里出现。


综上,代码如下:

     public static int findOnce(int []a,int Times){      int tmp =0 ;      int[] bigCount = new int[32];      for(int i=0;i<a.length ;i++){      for(int j=0;j<32;j++){      //bigCount[j] += ((a[i]>>j) & 1);      bigCount[j] += ((a[i] & (1<<j))==0 ? 0:1);      }      }      for(int j=0;j<32;j++){      if(bigCount[j]%Times != 0){      tmp += (1<<j);        }      }      return tmp;      }




0 0
原创粉丝点击