zoukankan      html  css  js  c++  java
  • LeetCode 136. Single Number

    原题链接在这里:https://leetcode.com/problems/single-number/

    题目:

    Given an array of integers, every element appears twice except for one. Find that single one.

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

    题解:

    首先会想到HashMap,HashSet的想法,但会用到extra O(n) space.

    所以就要用到bit manipulation,这里和Single Number II非常相似, 32位的int, 每一位的count若是出现奇数,那么这一位就是用来组成single number的.

    但这里有个更快的方法,就是用异或 ^ operator. 异或 every number in the array and the result would be the single number.

    Method 1 Time Complexity: O(n). Space: O(n).

    Method 2 Time Complexity: O(n). Space: O(1).

    Method 3 Time Complexity: O(n). Space: O(1).

    AC Java:

     1 public class Solution {
     2     public int singleNumber(int[] nums) {
     3         /*Method 1
     4         if(nums == null || nums.length == 0)
     5             return Integer.MIN_VALUE;
     6         
     7         HashSet hs = new HashSet();
     8         for(int i = 0; i < nums.length; i++){
     9             if(!hs.contains(nums[i])){
    10                 hs.add(nums[i]);
    11             }else{
    12                 hs.remove(nums[i]);
    13             }
    14         }
    15         
    16         Iterator it = hs.iterator();
    17         int res = Integer.MIN_VALUE;
    18         while(it.hasNext()){
    19             res = (int)it.next();
    20         }
    21         
    22         return res;
    23         */
    24         
    25         /*Method 2
    26         if(nums == null || nums.length == 0)
    27             return Integer.MIN_VALUE;
    28             
    29         int [] bitCounter = new int[32];
    30         for(int i = 0; i<32; i++){
    31             for(int j = 0; j<nums.length; j++){
    32                 bitCounter[i] += (nums[j]>>i&1); //error
    33             }
    34         }
    35         int res = 0;
    36         for(int i = 0; i<32; i++){
    37             res += (bitCounter[i]%2)<<i;
    38         }
    39         return res;
    40         */
    41         
    42         //Method 3
    43         if(nums == null || nums.length == 0)
    44             return Integer.MIN_VALUE;
    45         int res = 0;
    46         for(int j = 0; j < nums.length; j++){
    47             res = res ^ nums[j];
    48         }
    49         return res;
    50     }
    51 }

    跟上Single Number IISingle Number III.

  • 相关阅读:
    关于异步IO与同步IO的写操作区别
    慢慢开始记录一些技术心得吧
    写了placement new就要写placement delete
    关于针对class自定义new操作符失败的函数处理
    operator->和operator->*
    关于继承中的拷贝构造函数
    关于g++编译模板类的问题
    关于互斥锁,条件变量的内核源码解析
    关于sigwait
    观察者设计模式
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4825048.html
Copyright © 2011-2022 走看看