Single Number
来源:互联网 发布:大华7016软件 编辑:程序博客网 时间:2024/05/01 16:30
SingleNumber 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?
public class Solution { public static int singleNumber(int[] nums) { // if(nums.length == 1) return nums[0]; int result = 0; for (int i = 0; i < 32; i++) { int cnt = 0; int bit = 1 << i; for (int num : nums) { if ((num & bit) != 0) { 等于零不用计 result本来就是零 去掉这个判断的话 cnt每次都等于nums.length没用了 cnt++; } } cnt %= 3; if (cnt == 1) result |= bit; } return result; } }
public class Solution { public int singleNumber(int[] nums) { Arrays.sort(nums); int i=0; while(i<nums.length-1){ if(nums[i]==nums[i+2]) i=i+3; else return nums[i]; } return nums[i]; }}
public class Solution { public int singleNumber(int[] nums) { Arrays.sort(nums); int i=0; while(i<nums.length-1){ if(nums[i]==nums[i+1]) i=i+2; else return nums[i]; } return nums[i]; }}
异或运算具有交换性,1异或2 异或2==1异或(2异或2) 两个相同的数异或得0,任何数与0异或得原值
public class Solution { public int singleNumber(int[] nums) { int result=0; for(int i=0;i<nums.length;i++){ result^=nums[i]; } return result; }}
260. Single Number III
save to favorite
Given an array of numbers nums
, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.
For example:
Given nums = [1, 2, 1, 3, 2, 5]
, return [3, 5]
.
public class Solution { public int[] singleNumber(int[] nums) { Arrays.sort(nums); int i=0,j=0; int [] result=new int[2]; while(i<nums.length-1){ if(nums[i]==nums[i+1]) i=i+2; else { result[j++]=nums[i]; i++; if(j==2) break; } } if(j==1) result[1]=nums[i]; return result; }}
public class Solution { public int[] singleNumber(int[] nums) { // Pass 1 : // Get the XOR of the two numbers we need to find int diff = 0; for (int num : nums) { diff ^= num; } // Get its last set bit diff &= -diff; // Pass 2 : int[] rets = {0, 0}; // this array stores the two numbers we will return for (int num : nums) { if ((num & diff) == 0) // the bit is not set { rets[0] ^= num; } else // the bit is set { rets[1] ^= num; } } return rets; }}
0 0
- Single Number
- single number
- Single Number
- Single Number
- Single Number
- Single Number
- Single Number
- Single Number
- Single Number
- Single Number
- Single Number
- Single Number
- Single Number
- Single Number
- single number
- Single Number
- Single Number
- Single Number
- 贪心算法
- import static和import的区别
- 瑞士轮
- 11个审查Linux是否被入侵的方法
- 设计模式之模版方法模式
- Single Number
- 有return的情况下try catch finally的执行顺序
- Android5.1.1-APK签名校验分析和修改源码绕过签名校验
- Linux内核CPU负载均衡机制
- PC网站扫一扫获取微信授权用户注册
- 内部类
- JS中substr和substring的用法和区别
- 判断控件的状态是显示(SW_SHOW)还是隐藏(SW_HIDE)
- 聊聊并发(四)深入分析ConcurrentHashMap