zoukankan      html  css  js  c++  java
  • LeetCode

    链接

    268. Missing Number

    题意

    消失的数字
    给定一个数组,包含了n个不同的数(从0到n),注意其中缺少了一个数。找出这个数。

    思路

    • 思路一:
      首先对该数组排序,直接遍历该数组,缺少哪个数字直接返回
    • 思路二:
      来自讨论区,由于abb = a。因此可以遍历数组,假设数组没有缺失的数字,那么xor = xor ^ i ^ nums[i]的值是一直不变的。但因为缺失了一个数,若该数不是最后一个数,那么会造成某一部分i不等于nums[i]的值,但后续的i+1又会将nums[i]抵消。因此到了最后,xor = 消失的数 ^ nums[nums.length - 1]。因此只需将xor ^ i即得答案(此时i的值即等于nums[nums.length - 1])。若缺失了最后一个数,之前的i ^ nums[i]全部被抵消,i本身即消失的数,最后返回xor(0) ^ i = i 即为答案。
    • 思路三:
      直接将所有实际值累加,再将下标值累加。相减即得答案。

    代码

    
        public int missingNumber(int[] nums) {
            Arrays.sort(nums);
            for (int i = 0; i < nums.length; i++) {
                if (nums[i] != i) return i;
            }
            return nums[nums.length-1] + 1;
        }
    
    
        public int missingNumber(int[] nums) {
            int xor = 0, i = 0;
            for (i = 0; i < nums.length; i++) {
    	    xor = xor ^ i ^ nums[i];
            }
            return xor ^ i;
        }
    
    
    
        public int missingNumber(int[] nums) {
            int sum=0;
            for(int i=0;i<nums.length;i++){
                sum+=nums[i];         
            }       
            int maxSum=0;
            for(int i=0;i<=nums.length;i++){
                maxSum+=i;
            }     
            return maxSum-sum; 
        }
    
  • 相关阅读:
    线性反馈系统
    静磁场
    平面波的传播
    Partition does not end on cylinder boundary
    FFTW简介及使用
    EINTR、ERESTARTSYS和SIGINT
    凉面
    linux Shell编程
    Linux From Scratch [2]
    Linux From Scratch [1]
  • 原文地址:https://www.cnblogs.com/zyoung/p/6897658.html
Copyright © 2011-2022 走看看