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?

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

    解题思路:

    在最后添加一个-1值,对数组从0-N对每个数字进行归位,最后数字不符合的就是丢失的那个数字。

    1. class Solution {  
    2. public:  
    3.     int missingNumber(vector<int>& nums) {  
    4.         if(nums.size()==0) return 0;  
    5.         nums.push_back(-1);  
    6.         for(int i=0;i<nums.size();i++){  
    7.             int temp;  
    8.             int index=nums[i];  
    9.             if(index==-1) break;  
    10.               
    11.             while(1){  
    12.                 temp = nums[index];  
    13.                 nums[index] = index;  
    14.                 if(temp == nums[index] || temp ==-1) break;  
    15.                 index = temp;  
    16.             }  
    17.               
    18.         }  
    19.          for(int i=0;i<=nums.size();i++)  
    20.           if(nums[i]!=i) return i;  
    21.           
    22.     }  
    23. };  
  • 相关阅读:
    mySQL练习题
    JAVA实现C/S结构小程序
    JavaLinkedHashSet练习
    关于Extjs删除分页后删除最后一条数据页面无效的问题。
    hibernate 插入,更新数据库错误
    错误!错误!错误!
    坑爹的oracle
    关于hibernate实体类
    第一个项目的需求分析
    Ueditor 单独使用上传图片及上传附件方法
  • 原文地址:https://www.cnblogs.com/liangyc/p/8847510.html
Copyright © 2011-2022 走看看