zoukankan      html  css  js  c++  java
  • leetcode268

    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?

    开场暖身算法:排序后找O(logn), O(1)。hashSet先全加进去再一个个删看剩下的O(n), O(n)。
    最优算法:桶排序思想。 O(n), O(1)。
    本题假设数字应该呆的index就是数字本身。第一次扫描把所有数字换到自己应该呆的位置上。第二次扫描哪个位置上出现了错误的数字,那么期待的那个数字就是丢失的数字。(如果所有位置上都对了,那丢的是最后那个数字)。
    类似题目:first missing positive。https://www.cnblogs.com/jasminemzy/p/9654890.html

    实现:

    class Solution {
        public int missingNumber(int[] nums) {
            for (int i = 0; i < nums.length; i++) {
                while (nums[i] != i && nums[i] < nums.length) {
                    swap(nums, i, nums[i]);
                }
            }
            for (int i = 0; i < nums.length; i++) {
                if (nums[i] != i) {
                    return i;
                }
            }
            return nums.length;
        }
        
        private void swap(int[] nums, int i, int j) {
            int temp = nums[i];
            nums[i] = nums[j];
            nums[j] = temp;
        }
    }
  • 相关阅读:
    01JAVA语言基础课后作业
    从命令行接收多个数字,求和之后输出结果
    java伪代码
    java从命令行接收多个数字,求和之后输出结果
    大道至简读后感
    大道至简读后感
    d3d两点
    codeforce 1A-1C
    计算几何里三角形的一些姿势,都忘干净了..
    c++ template 5.x 学习总结
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/9736864.html
Copyright © 2011-2022 走看看