[LeetCode] 137. Single Number II 单独数 II
Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input: [2,2,3,2] Output: 3
Example 2:
Input: [0,1,0,1,0,1,99] Output: 99
解法:参考
Java:
1 2 3 4 5 6 7 8 | public int singleNumber( int [] A) { int ones = 0 , twos = 0 ; for ( int i = 0 ; i < A.length; i++){ ones = (ones ^ A[i]) & ~twos; twos = (twos ^ A[i]) & ~ones; } return ones; } |
Python:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | class Solution( object ): def singleNumber( self , nums): """ :type nums: List[int] :rtype: int """ x1, x2, mask = 0 , 0 , 0 for i in nums: x2 ^ = x1 & i; x1 ^ = i; mask = ~(x1 & x2); x2 & = mask; x1 & = mask; return x1 |
C++:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | class Solution { public : int singleNumber(vector< int >& nums) { int one = 0, two = 0, three = 0; for ( int i = 0; i < nums.size(); ++i) { two |= one & nums[i]; one ^= nums[i]; three = one & two; one &= ~three; two &= ~three; } return one; } }; |
C++:
1 2 3 4 5 6 7 8 9 10 11 | class Solution { public : int singleNumber(vector< int >& nums) { int a = 0, b = 0; for ( int i = 0; i < nums.size(); ++i) { b = (b ^ nums[i]) & ~a; a = (a ^ nums[i]) & ~b; } return b; } }; |
类似题目:
[LeetCode] 136. Single Number 单独数
[LeetCode] 260. Single Number III 单独数 III
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· C++代码改造为UTF-8编码问题的总结
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· 为DeepSeek添加本地知识库
· 精选4款基于.NET开源、功能强大的通讯调试工具
· DeepSeek智能编程
· 大模型工具KTransformer的安装
· [计算机/硬件/GPU] 显卡