Single Number:
1. Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
代码:
1 2 3 4 5 6 7 8 9 10 | class Solution { public : int singleNumber( int A[], int n) { int result = 0; for ( int i = 0; i < n; ++i){ result ^= A[i]; } return result; } }; |
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?
方法1:(分别计算各位1的个数 mod 3)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | class Solution { public : int singleNumber( int A[], int n) { int count[32] = {0}; int result = 0; int bit = sizeof ( int ) * 8; for ( int i = 0; i < n; ++i) { for ( int j = 0; j < bit; ++j){ if ((A[i] >> j) & 0x1) count[j] = (count[j] + 1) % 3; } } for ( int i = 0; i < bit; ++i){ result |= (count[i] << i); } return result; } }; |
方法2:(三个变量,分别记录出现一次,出现两次,出现三次的值)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class Solution { public : int singleNumber( int A[], int n) { int one, two, three; one = two = three = 0; for ( int i = 0; i < n; ++i){ two |= (one & A[i]); one ^= A[i]; three = ~(one & two); one &= three; two &= three; } return one; } }; |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步