您的位置:首页 > 其它

leetcode-Single Number

2016-04-25 20:17 411 查看
136.Single Number I

Given an array of integers, every element appearstwiceexcept for one. Find that single one.

Note:

Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

解析:

异或操作定义: 相同为假,不同为真。

如果两个元素相同,异或操作后为0 ,则剩余的单个元素与0 异或,还为本身。

复杂度:

时间 O(N)

代码:

public class Solution {
public int singleNumber(int[] nums) {
for (int i = 1 ; i<nums.length; i++){
nums[0] ^= nums[i];
}
return nums[0];
}
}


137. 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?

解析:

每个元素均出现3次(一个元素除外),找出该单个元素。同样利用位操作,一个数出现3次,那么对第i位而言,不是全为0 就是全为1, 对第i位的数累加,如果单个元素第i位为0 ,则比能被3整除;不为0 ,则模3 余1 。 该解法的是时间复杂度为 o(32* n) , 一个int型占32位。

复杂度:

时间 O(N^2)

代码:

public class Solution {
public int singleNumber(int[] nums) {
int[] count =new int[32];
int result = 0;
for(int i = 0; i < 32; i++){
for(int j =0; j<nums.length; j++){
if((nums[j] & 1) == 1){
count[i]++;
}
nums[j] = (nums[j]>>1);
}
result |= ((count[i]%3) << i);  //大循环为32,每次左移,或操作 很精简!
}
return result;
}
}


138. Single Number III

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].

Note:

The order of the result is not important. So in the above example, [5, 3] is also correct.

Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?

解析:

首先对所有元素进行异或操作,则结果为两个所求元素的异或结果,如100010。则可以根据最低位1 所在位置 i对所有元素进行区分,(1说明这两个元素在i位上取值必不相同,其余元素均成对出现,均为1,或均为0 ),区分后,同样根据异或进行求解(原理类似题136)。

复杂度:

时间 O(N)

代码:

public class Solution {
public int[] singleNumber(int[] nums) {
// 求 两所求元素的异或值
int tmp = 0;
for (int num : nums) {
tmp ^= num;
}

tmp &= ~(tmp-1);  // 仅保留二进制位为1的<span style="font-family: Arial, Helvetica, sans-serif;">最低位</span><span style="font-family: Arial, Helvetica, sans-serif;">.</span>

int[] rets = {0, 0}; // 需返回两个元素
for (int num : nums)
{
if ((num & tmp) == 0) //根据该二进制位是否为1 将数组分隔。
{
rets[0] ^= num;
}
else
{
rets[1] ^= num;
}
}
return rets;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: