zoukankan      html  css  js  c++  java
  • 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;
        }
    }
  • 相关阅读:
    bzoj:1299: [LLH邀请赛]巧克力棒
    [51nod][cf468D]1558 树中的配对
    HDU5447 Good Numbers
    Timus Online Judge:ural:1006. Square Frames
    poj1830:开关问题
    bzoj:1776: [Usaco2010 Hol]cowpol 奶牛政坛
    bzoj:1725: [Usaco2006 Nov]Corn Fields牧场的安排
    bzoj:1828: [Usaco2010 Mar]balloc 农场分配
    bzoj:1584: [Usaco2009 Mar]Cleaning Up 打扫卫生
    bzoj:1598: [Usaco2008 Mar]牛跑步
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10039518.html
Copyright © 2011-2022 走看看