数组中除一个元素外其他所有元素出现二或三次,找到只出现一次的元素
2016-04-01 10:13
519 查看
1、数组中除一个元素外其他所有元素出现二,找到只出现一次的那个元素。
2、数组中除一个元素外其他所有元素出现三次,找到只出现一次的那个元素。
3、数组中所有元素出现两次,其中有两个元素只出现一次,找出这两个元素。
public int singleNumber(int[] nums) { int res = nums[0]; for (int i = 1; i < nums.length; i++) res = res ^ nums[i]; return res; }
2、数组中除一个元素外其他所有元素出现三次,找到只出现一次的那个元素。
public static int singleNumber(int[] nums) { int len = nums.length, result = 0; for (int i = 0; i < 32; i++) { int sum = 0; for (int j = 0; j < len; j++) { sum += (nums[j] >> i) & 1; } result |= (sum % 3) << i; } return result; }
3、数组中所有元素出现两次,其中有两个元素只出现一次,找出这两个元素。
public static int[] geTwoEle(int[] res){ if(res.length==2)return res; int []val=new int[2]; int temp=res[0]; for(int i=1;i<res.length;i++){ temp^=res[i]; } //find the leftmost pos where two element is different int i=0; while(temp!=0)temp>>=++i; i--; int left[]=new int[res.length]; int right[]=new int[res.length]; int lefti=0; int righti=0; //split val array into two arrays according to the different pos for(int j=0;j<res.length;j++){ if(((res[j]>>i)&1)==0){ left[lefti++]=res[j]; }else{ right[righti++]=res[j]; } } //in left and right array only one element is different,use ^ to find the element val[0]=left[0]; for(int j=1;j<lefti;j++){ val[0]^=left[j]; } val[1]=right[0]; for(int j=1;j<righti;j++){ val[0]^=right[j]; } return val; }
相关文章推荐
- Android TouchEvent事件传递机制
- ffmpeg的headers设置
- sqlplus命令的使用大全
- Go语言中的错误处理系统
- 把数组排成最小的数
- xUtils3.0 db数据库操作笔记1
- [C++]各种排序方法
- socket.io简介
- vc 递归删除非空文件夹
- Linux 2.6 调度系统分析
- mysql 5.5安装
- Xcode7找不到.dylib解决方法
- 通过JAVA在命令行(如控制台)运行Shell指令
- linux下验证码功能不能正常显示
- java怎么判断一个文本是什么编码格式以及运行在doc下,javadoc注释文档
- UsageStatsManager.queryUsageStats的参数interval
- 栈解决回文
- 2016SDAU编程练习一1003
- 关于 C/C++ 的文章
- .top域名总量15强:中国数据被赶超 阿里云晋身五强