首页 > 代码库 > Leetcode - Single Number II
Leetcode - Single Number II
The key is to use two constant space(32 bits) to store how many times 1 or 0 showed up in the bit i. If times of 1 in bit i is not the multiple of 3, then the unique value‘s bit i is 1. Otherwise the unique value‘s bit i is 0.
Actually this algorithm can be extended to three times, four times, five times etc..
import java.util.*; public class Solution { public int singleNumber(int[] A) { int[] zero = new int[32]; int[] one = new int[32]; for(int i=0;i<A.length;i++) { for(int j=0;j<32;j++) { if( ((1<<j) & A[i]) != 0 ) { one[j]++; } else { zero[j]++; } } } int ans = 0; for(int k=0;k<32;k++) { if(one[k] % 3 !=0 ) { ans = (ans | (1<<k)); } } return ans; } public static void main(String[] args) { int[] A = {-1,5,5,5}; Solution sol = new Solution(); System.out.println(sol.singleNumber(A)); } }
Leetcode - Single Number II
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。