• 41. First Missing Positive


    Given an unsorted integer array, find the smallest missing positive integer.

    Example 1:

    Input: [1,2,0]
    Output: 3
    

    Example 2:

    Input: [3,4,-1,1]
    Output: 2
    

    Example 3:

    Input: [7,8,9,11,12]
    Output: 1
    

    Note:

    Your algorithm should run in O(n) time and uses constant extra space.

     1 class Solution {
     2     public void swap(int[] nums, int a, int b){
     3         int temp = nums[a];
     4         nums[a] = nums[b];
     5         nums[b] = temp;
     6     }
     7     public int firstMissingPositive(int[] nums) {
     8         int n = nums.length;
     9         int i = 0;
    10         while (i < n) {
    11             if (nums[i] > 0 && nums[i] <= n) {
    12                 if (i != nums[i] - 1  
    13                     && nums[i] != nums[nums[i] - 1]) {
    14                     swap(nums, i, nums[i] - 1);
    15                 } else {
    16                     i++;
    17                 }
    18             } else {
    19                 i++;
    20             }
    21         }
    22         
    23         int ans = -1;
    24         for (i = 0; i < n; ++i) {
    25             if (nums[i]  != i + 1) {
    26                 ans = i + 1;
    27                 
    28                 break;
    29             }
    30         }
    31         
    32         return ans == -1 ? n + 1 : ans;
    33     }
    34 }
  • 相关阅读:
    路由配置系统(URLconf)
    Django常见命令
    MVC框架和MTV框架
    Django基础
    服务器程序和应用程序
    自定义web框架
    HTTP协议对收发消息的格式要求
    web框架的本质
    python国内镜像源
    Scrapy框架安装失败解决办法
  • 原文地址:https://www.cnblogs.com/hyxsolitude/p/12317667.html
Copyright © 2020-2023  润新知