问题
我们必须找到只出现过一次的数字。
暴力方法是使用 hashmap 来跟踪值的计数,然后返回 count =1 的值;
使用位操作的最佳方法:
我们知道对于所有其他组合,1^0 = 1、0 ^1 = 1、0 ^ 0 = 0、1 ^ 1= 0。
这意味着对于相同的值,异或给出 0,因此如果我们异或数组中的所有值,它将只给出计数为 1 的数字(因为其余值将变成 0)
tc:o(n)
sc:o(1)
class Solution { public int singleNumber(int[] nums) { int single = nums[0]; for(int i =1;i<nums.length;i++){ single = single^nums[i]; } return single; } }
以上就是单号I的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号