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?

    //Time: O(n), Space: O(1)
    //Approach 1 : 用前n+1项和公式减去nums里面的每一个值,剩下的就是missing number
    public int missingNumber(int[] nums) {
            if (nums == null || nums.length == 0) {
                return -1;
            }
            
            int result = 0;
            
            for (int i = 0; i < nums.length; i++) {
                result += nums[i];
            }
            
            return nums.length * (nums.length + 1) / 2 - result;
    
    //Approach 2: XOR
        public int missingNumber(int[] nums) {
            if (nums == null || nums.length == 0) {
                return -1;
            }
            
            int result = 0;
            for (int i = 0; i < nums.length; i++) {
                result = result ^ i ^ nums[i];
            }
            
            return result ^ nums.length;//最后不要忘记异或最后一个数
        }
    //Approach 3: 如果是排序好的数组,可以用二分法time为O(logn), 否则排序time是O(nlogn)
    代码略
  • 相关阅读:
    Cookies的实际存储位置
    搭建Git本地服务器
    在Tomcat中部署war
    Server.xml配置解析
    Tomcat配置详解,配置文件server.xml详解
    将centos7打造成桌面系统
    英语词汇大全
    商场/超市常见英语标识
    商务英语词汇大全
    常用繁体字大全
  • 原文地址:https://www.cnblogs.com/jessie2009/p/9774059.html
Copyright © 2011-2022 走看看