博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode - First Missing Positive
阅读量:6970 次
发布时间:2019-06-27

本文共 1074 字,大约阅读时间需要 3 分钟。

题目:

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

For example,

Given [1,2,0] return 3,
and [3,4,-1,1] return 2.

思路:

不断进行交换,将值为 i 的数字交换到 (i - 1)th 的位置.

package array;public class FirstMissingPositive {    public int firstMissingPositive(int[] nums) {        int n;        if (nums == null || (n = nums.length) == 0) return 1;        for (int i = 0; i < n; ++i) {            int a = nums[i];            while (a > 0 && a <= n && nums[i] != i + 1 && nums[a - 1] != a) {                swap(nums, i, a - 1);                a = nums[i];            }        }                int j = 0;        while (j < n && nums[j] == j + 1){            ++j;        }        return j + 1;    }        private void swap(int[] nums, int i, int j) {        int tmp = nums[i];        nums[i] = nums[j];        nums[j] = tmp;    }        public static void main(String[] args) {        // TODO Auto-generated method stub        int[] nums = { 1,1 };        FirstMissingPositive f = new FirstMissingPositive();        System.out.println(f.firstMissingPositive(nums));    }}

 

转载地址:http://mxfsl.baihongyu.com/

你可能感兴趣的文章
Orchard模块开发全接触4:深度改造前台
查看>>
“Incompatible clusterIDs”错误原因分析
查看>>
以stm32f407为例,学习cortex-m4通用寄存器的用法
查看>>
WPF BitmapSourceToArray and ArrayToBitmapSource
查看>>
[日记]2014-9-21.
查看>>
《你必须掌握的Entity Framework 6.x与Core 2.0》书籍出版
查看>>
DUP
查看>>
How does “void *” differ in C and C++?
查看>>
pl/sql设置快捷键输入sf+空格出现select * from
查看>>
Mybatis_IllegalArgumentException: Mapped Statements collection does not contain value for
查看>>
common commands on Linux
查看>>
常用的数据分析方法汇总
查看>>
【轻松搞定系统操作访问文件没权限的问题】
查看>>
flex简单参考实例
查看>>
谈谈嵌套for循环的理解
查看>>
简单递归写侧边菜单栏
查看>>
PeopleSoft Audit
查看>>
支付宝 快捷支付 需要注意的事情
查看>>
java中常见异常总汇,附解释
查看>>
CSRF 攻击的应对之道
查看>>