【Leetcode】first-missing-positive

题目描述

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

For example,
Given[1,2,0]return3,
and[3,4,-1,1]return2.

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

题目解释

给一个无序的整数数组,找出第一个缺失的正整数

易懂的栗子:

[2,3,4,5,6],返回1

[1,2,3,5,6],返回的4

解题思路

一次遍历,归位,将值为i的数放到数据下标为i-1的位置;

二次遍历,取结果,遍历归位后的数组,满足a[i]!=i+1的值i+1即为所求结果

代码

public static int firstMissingPositive(int[] a) {
		if (a == null || a.length == 0) {
			return 1;
		}
		int len = a.length;
		// 第一次遍历,将值为k的数放到下标数组下标为k-1的位置
		for (int i = 0; i < len; ++i) {
			while (a[i] > 0 && a[i] <= len && a[i] != i + 1 && a[i] != a[a[i] - 1]) {
				int temp = a[i];
				a[i] = a[temp - 1];
				a[temp - 1] = temp;
			}
		}
		// 第二次遍历,取出第一个缺失的正整数
		for (int i = 0; i < len; ++i) {
			if (a[i] != i + 1) {
				return i + 1;
			}
		}
		return len + 1;
	}

时空复杂度

空间复杂度为O(1),在数组原地进行的排序。

时间复杂度分析:

扫描二维码关注公众号,回复: 3881325 查看本文章

看下算法的基本操作,最坏情况下[5,1,2,3,4],重复执行次数为n,n为数组大小(a[i]!=a[a[i]-1]限制了while循环内的操作最多执行n次,如果不加这个条件,那么当数组中有数据重复时,将陷入死循环)。

// 第一次遍历,将值为k的数放到下标数组下标为k-1的位置
		for (int i = 0; i < len; ++i) {
			while (a[i] > 0 && a[i] <= len && a[i] != i + 1 && a[i] != a[a[i] - 1]) {
				int temp = a[i];
				a[i] = a[temp - 1];
				a[temp - 1] = temp;
			}
		}

经验和教训

1.基于计数排序的这种思想,可以对一定范围内的整数排序

2.读题读了十分钟,没读懂在讲啥,智商堪忧

2.牛客不支持python答题了?!。。

猜你喜欢

转载自blog.csdn.net/baidu_29894819/article/details/83306978
今日推荐