leetcode268 - Missing Number - easy

來源:互聯網
上載者:User

標籤:extra   int   wap   就是   etc   swap   vat   ...   set   

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;    }}

 

leetcode268 - Missing Number - easy

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.