Java实现LeetCode_0041_FirstMissingPositive

package javaLeetCode.hard;

import java.util.Arrays;

public class FirstMissingPositive_41 {
	public static void main(String[] args) {
		int []nums = {0,2,2,1,1};
		System.out.println(firstMissingPositive(nums));
	}//end main()
	
	/**
	 * 
	 * */
	
	/*
	 * Test Data:
	 * 1. {3,4,-1,1}--2
	 * 2. {7,8,9,11,12}--1
	 * 3. {1,2,0}--3
	 * 4. {0}--1
	 * 5. {1000,-1}--1
	 * 6. {0,2,2,1,1}--3
	 * */
	public static int firstMissingPositive(int[] nums) {
		if (nums == null) {
			return -1;
		} // end if
		int firstPos = -1;// First positive position;
		int misPos = -1;// Missing positive;
		Arrays.sort(nums);
		// Find the position of the first positive number.
		if (nums.length == 0 || nums[0] > 1 || nums[nums.length - 1] < 0) {
			misPos = 1;
		} else {
			for (int i = 0; i < nums.length; i++) {
				if (nums[i] >= 0) {
					firstPos = i;
					if (nums[firstPos] > 1) {
						return 1;
					} else {
						break;
					} // end if
				} else {
					continue;
				} // end if
			} // end for
			//
			for (; firstPos < nums.length - 1; firstPos++) {
				if (nums[firstPos + 1] - nums[firstPos] > 1) {
					misPos = nums[firstPos] + 1;
					break;
				} else {
					continue;
				} // end if
			} // end for
				// If the firstPos equals last index of the array of "nums".
			if (firstPos == nums.length - 1) {
				misPos = nums[nums.length - 1] + 1;
			} // end if
		} // end if

		return misPos;
	}// end firstMissingPositive()
}//end FirstMissingPositive_41 


  • 20
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 26
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 26
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值