• 260. 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:

    1. The order of the result is not important. So in the above example, [5, 3] is also correct.
    2. Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity

    本题和single number1,2不同之处在于,本题有两个single number,其他都是成对存在的,我们首先可以考虑,a&(-a)为什么,他的结果是从右面数第一个1,而我们知道,singnumber1^singnumber2==a,说明1和2的位不同数是a,则右面数第一个不同位就是a&(-a),这也是可以把它们区别开的办法,代码如下:

     1 public class Solution {
     2     public int[] singleNumber(int[] nums) {
     3         int[] res = new int[2];
     4         int xor = 0;
     5         for(int i=0;i<nums.length;i++){
     6             xor= xor^nums[i];
     7         }
     8         xor = xor&(-xor);
     9         for(int i=0;i<nums.length;i++){
    10             if((xor&nums[i])==xor){
    11                 res[0]=res[0]^nums[i];
    12             }else{
    13                 res[1] = res[1]^nums[i];
    14             }
    15         }
    16         return res;
    17     }
    18 }
  • 相关阅读:
    UBUntu 软件 源配置方法
    oracle 11G direct path read 非常美也非常伤人
    iOS多线程编程(四)------ GCD(Grand Central Dispatch)
    Yii之路(第八)
    UVA
    我喜欢的网易云音乐
    LeetCode_DP_Word Break II
    管理Java垃圾回收的五个建议
    const成员函数总结
    算法之经典排序算法小归纳
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6380485.html
Copyright © 2020-2023  润新知