zoukankan      html  css  js  c++  java
  • [LeetCode] 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?

    感谢cnblog博主feiling,这篇博客一方面参考了feiling的博客,也加入了自己的一些看法。

    [解题思路]

    要求线性时间复杂度,同时空间复杂度为O(1),即只允许开常数个空间。

    最直接的思路是对每一个元素尝试查找是否有重,如果没有重,就返回。

    class Solution {
    public:
        int singleNumber(int A[], int n) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            int i = 0, j = 0;
            int ans = 0;
            for(i = 0;i < n;i++)
            {
                for(j = 0;j < n;j++)
                {
                    if(i == j)
                        continue;
                    else if(A[i] == A[j])
                        break;
                        else continue;
                }
                
                if(j == n)
                    return A[i];
            }
        }
    };

    不幸的是虽然是o(n2)的时间复杂度,但是还是超时了。于是乎就得想一个o(n)的算法。

    o(n)的算法只能是线性扫描一遍,可能的相法是位运算。对于异或来说:

    1. 异或运算是可交换,即 a ^ b = b ^ a

    2. 0 ^ a = a

    那么如果对所有元素做异或运算,其结果为那个出现一次的元素,理解是a1 ^ a2 ^ ....,可以将所有相同元素交换至相邻位置,首先运算相同元素,则会产生(n - 1)/2个0异或积,剩余一个单一元素,他们的异或积为这个单一元素自己,得解。

    复制代码
     1 public class Solution {
     2     public int singleNumber(int[] A) {
     3         // Note: The Solution object is instantiated only once and is reused by each test case.
     4         if(A == null || A.length == 0){
     5             return 0;
     6         }
     7         int result = A[0];
     8         
     9         for(int i = 1; i < A.length; i++){
    10             result = result ^ A[i];
    11         }
    12         return result;
    13     }
    14 }
    复制代码

    本题扩展

    1.一个数组中有两个元素只出现一次,其他所有元素都出现两次,求这两个只出现一次的元素

    [解题思路]

    将数组所有元素都进行异或得到一个不为0的结果,根据这个结果中的不为0的某一位将数组分成两组

    将两组中的元素进行异或,如两个数组的异或值都不为0,则得到最后结果

    2.一个数组中有一个元素只出现1次,其他所有元素都出现k次,求这个只出现1次的元素

    [解题思路]

    当k为偶数时,同lss

    当k为奇数时,将数组中每个元素的每一位相加mod k,得到结果即位出现1次的元素,时间复杂度O(nlen),空间复杂度为O(1)

  • 相关阅读:
    Swagger入门
    UOS
    Java多线程
    英语语法小知识-Unit1
    MVVM
    Vue入门
    Mybatis入门
    Python pip install
    js 触发LinkButton点击事件,执行后台方法
    ajax 请求 ascx
  • 原文地址:https://www.cnblogs.com/changchengxiao/p/3413294.html
Copyright © 2011-2022 走看看