zoukankan      html  css  js  c++  java
  • LeetCode

    题目:

    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));
        }
    
    }
  • 相关阅读:
    maven错误
    angularjs的一点总结
    工具汇总
    重启outlook的bat脚本
    前端框架参考
    imply套件以及plyql的安装
    centos下nodejs,npm的安装和nodejs的升级
    kafka错误集锦
    动态规划DP笔记
    链接
  • 原文地址:https://www.cnblogs.com/null00/p/5075525.html
Copyright © 2011-2022 走看看