zoukankan      html  css  js  c++  java
  • LeetCode 268. Missing Number

    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.

    For example,
    Given nums = [0, 1, 3] return 2.

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

    Credits:
    Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.


    【题目分析】

    从0,1,2,...,n这n+1个数中选择n个数,找出这n个数中缺失的那个数。


    【思路】

    1. 累加

    计算1+2+...+n. 用和值减去数组中数的和值,最后的差就是我们要的结果。这个过程中要防止溢出。

    2. 异或

    异或运算有一个性质,x^y^y=x. 结果与x和y的顺序无关。我们把0~n与数组中的数都异或到一起,那么最后的结果就是缺失的那个数。

    3. 二分查找

    把数组排序,用二分查找来找到缺失值。


    【java代码1】

     1 public class Solution {
     2     public int missingNumber(int[] nums) {
     3         int res = 0;
     4         for(int i = 1; i <= nums.length; i++) {
     5             res += (i-nums[i-1]);
     6         }
     7         
     8         return res;
     9     }
    10 }

    【java代码2】

    1 public int missingNumber(int[] nums) { //xor
    2     int res = nums.length;
    3     for(int i=0; i<nums.length; i++){
    4         res ^= i;
    5         res ^= nums[i];
    6     }
    7     return res;
    8 }

    【java代码3】

     1 public int missingNumber(int[] nums) { //binary search
     2     Arrays.sort(nums);
     3     int left = 0, right = nums.length, mid= (left + right)/2;
     4     while(left<right){
     5         mid = (left + right)/2;
     6         if(nums[mid]>mid) right = mid;
     7         else left = mid+1;
     8     }
     9     return left;
    10 }
     
  • 相关阅读:
    两种存储思路
    越来越浅
    我了解的前端史
    关于称赞小孩
    怎么写递归
    Python笔记(十八):协程asyncio
    网络协议笔记(一):HTTP协议基础知识
    Linux笔记(三):常用命令
    算法笔记(九):二分查找
    数据结构笔记(二):栈、队列
  • 原文地址:https://www.cnblogs.com/liujinhong/p/6490254.html
Copyright © 2011-2022 走看看