LeetCode136,137寻找只出现一次的数
2024-08-30 15:09:32
1.题目意思:在数组中,只有一个数字只出现了一次 其他的都出现了两次。找出那个只出现一次的数字。
//利用位运算 异或 两个相同的数字异或为0
public int singleNumber(int[] nums) {
int res = 0 ;
for (int i = 0; i < nums.length; i++) {
res ^=nums[i];
}
return res;
}
2.题目意思:数组中,每个数字都出现三次 除了只有一个数字只出现了一次。找出那个只出现一次的数字。
// 方法1:排序解
public static int singleNumber(int[] nums) {
Arrays.sort(nums);
int res = 0;
for (int i = 0; i < nums.length; i += 3) {
if (i == nums.length - 1) {
res = nums[i];
break; //continue 可以
}
if (nums[i] == nums[i + 1]) {
continue;
}else {
res = nums[i];
break;
}
}
return res;
}
//位运算解---没看懂---哪位大佬知道可以在下面告知我--万分感谢!!!!
public static int singleNumber1(int[] nums) {
int one = 0, two = 0;
for (int i : nums) {
one = (one ^ i) & ~two;// ~补位运算
two = (two ^ i) & ~one;
}
return one;
} //还有一种思路 : 就是用set集合存储,然后求和,然后乘3,减去原数组的和,在除以2---就是我想得到的数;
最新文章
- 循环写入Insert 与 SqlBulkcopy
- html5的小知识点小集合
- PHPCMS V9教程之快速入门
- 编写高质量JS代码的68个有效方法(九)
- XML文件操作学习(一)
- SharePoint咨询师之路:设计之前的那些事一:容量
- Live555中RTP包的打包与发送过程分析
- Spring Data JPA教程, 第八部分:Adding Functionality to a Repository (未翻译)
- openssl生成rsa公私钥
- js和HTML结合(补充知识:如何防止文件缓存的js代码)
- 【C#4.0图解教程】笔记(第19章~第25章)
- Windows phone 8 安装在 VMWare上错误的各种解决方案
- chrome开发工具指南(十)
- python3.5新增函数isclose的使用
- 02_HTML5+CSS详解第四天
- Hibernate--对象关系
- 实验6 shell程序设计一(1)
- 卢卡斯定理——应用hdu4349
- [math][mathematica] archlinux 下 mathematica 的安装 (科学计算软件 mathematica/matlab/sagemath)
- Qt布局管理: 停靠窗口QDockWidget类(纯代码实现)
热门文章
- MySQL-Tool:Navicate 安装
- js方式的页面跳转
- 真正认识 realloc 的工作方式(转载)
- bzoj 3503: [Cqoi2014]和谐矩阵【高斯消元】
- Activiti6.0教程 Service用途剖析 (二)
- 一步一步学习GTK
- Use Power bi Mobile Show SSRS 2016 Mobile Report;使用 Power BI Mobile 查阅ssrs2016 mobile report
- java的构造方法 this 重载
- C#关于html颜色值的转化 ColorTranslator
- js连续赋值,你理解了吗