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)
    代码略
  • 相关阅读:
    五、nginx 配置实例-负载均衡
    四、nginx配置实例-反向代理
    三、nginx配置文件
    二、Nginx 安装
    十二、rpm包的管理
    十一、进程管理
    十、Linux磁盘分区、挂载
    九、定时任务调度
    八、组管理和权限管理
    七、实用指令
  • 原文地址:https://www.cnblogs.com/jessie2009/p/9774059.html
Copyright © 2011-2022 走看看