[LeetCode] Single Number III
Try to split all the numbers into two groups with each of the target one in different groups. Refer to this link for a nice explanation.
The code is written as follows.
1 class Solution { 2 public: 3 vector<int> singleNumber(vector<int>& nums) { 4 int t = 0, p, first = 0, second = 0; 5 for (int num : nums) t ^= num; 6 for (p = 0; p < 32; p++) 7 if ((t >> p) & 1) break; 8 for (int num : nums) { 9 if ((num >> p) & 1) first ^= num; 10 else second ^= num; 11 } 12 return {first, second}; 13 } 14 };
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步