首页 > 代码库 > [Leetcode] Single Number II
[Leetcode] Single Number II
Given an array of integers, every element appears three times except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Solution:
看到大神的解法: http://www.mitbbs.com/article_t/JobHunting/32547143.html
整数的32个bits,出现次数mod 3后必余0, 1, 2,其中余1的就是答案
public int singleNumber(int[] A) { int n1=0,n2=0; for(int i=0;i<A.length;++i){ int n0=~(n1|n2); // 若非余1也非余2,就是余0了 n2=(n1&A[i])|(n2&~A[i]); // 若「原本就余2且bit为0」或「原本余1且bit为1」,则该bit更新后余2 n1=(n1&~A[i])|(n0&A[i]); // 若「原本就余1且bit为0」或「原本余0且bit为1」,则该bit更新后余1 } return n1; }
[Leetcode] Single Number II
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。