• 268. Missing Number


    Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.

    Example 1:

    Input: [3,0,1]
    Output: 2
    

    Example 2:

    Input: [9,6,4,2,3,5,7,0,1]
    Output: 8
    

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

    M1: 求和

    因为是由0~n组成的数组,只缺少一个数字,可以先通过公式计算出应有的和,再遍历数组一个个减去,剩下的数就是missing number

    时间:O(N),空间:O(1)

    class Solution {
        public int missingNumber(int[] nums) {
            int n = nums.length;
            int sum = n * (n + 1) / 2;
            for(int i = 0; i < n; i++) {
                sum -= nums[i];
            }
            return sum;
        }
    }

    M2: hash table

    hashset,扫描两次,第一次把nums中元素放进set,第二次遍历0~n,找出map中没有的元素

    time: O(n), space: O(n)

    class Solution {
        public int missingNumber(int[] nums) {
            Set<Integer> set = new HashSet<>();
            for(int n : nums) {
                set.add(n);
            }
            
            int res = 0;
            for(int i = 0; i <= nums.length; i++) {
                if(!set.contains(i)) {
                    res = i;
                    break;
                }
            }
            return res;
        }
    }

    hashset, 扫描两次,第一次把1~n所有元素加入set,第二次把nums中的元素从set中删除,剩下的就是missing number

    time: O(n), space: O(n)

    class Solution {
        public int missingNumber(int[] nums) {
            Set<Integer> set = new HashSet<>();
            for(int n : nums) {
                set.add(n);
            }
            for(int i = 1; i <= nums.length; i++) {
                if(!set.remove(i)) {
                    return i;
                }
            }
            return 0;
        }
    }

    M3: bit operation

    先把0~n全部xor,再对nums中的元素全部xor

    time: O(n), space: O(1)

    class Solution {
        public int missingNumber(int[] nums) {
            int res = 0;
            for(int i = 0; i <= nums.length; i++) {
                res ^= i;
            }
            for(int n : nums) {
                res ^= n;
            }
            return res;
        }
    }
  • 相关阅读:
    == Equals ReferenceEquals 比较
    数据库 数据类型
    C# 判断路径和文件存在
    OpenXml 2.0 读取Excel
    excel2003, 2007最大行列、sheet数
    将List中部分字段转换为DataTable中
    X64位PC上dsoframer兼容性问题
    winform 客户端 HTTP协议与服务端通信以及解决中文乱码
    VIsual Studio 2010 常用快捷键
    Web Pages(单页面模型)
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10039518.html
Copyright © 2020-2023  润新知