美文网首页
FirstMissingPositive

FirstMissingPositive

作者: 瞬铭 | 来源:发表于2019-04-18 19:23 被阅读0次

    https://leetcode.com/problems/first-missing-positive/submissions/

    • JAVA
     public int firstMissingPositive(int[] nums) {
            int res = 1;
            for (int i = 0; i < nums.length; i++) {
                //看看这个注释的和没注释的有什么区别,注释的这个代码有个大bug,当输入数组为[1,1]的时候,这个bug就显现了
                // while ((nums[i] != i + 1) && nums[i] > 0 && nums[i] <= nums.length) {
                while (nums[i] > 0 && nums[i] <= nums.length && (nums[nums[i] - 1] != nums[i])) {
                    int t = nums[i] - 1;
                    int tmp = nums[i];
                    nums[i] = nums[t];
                    nums[t] = tmp;
                }
            }
            int i = 0;
            for (i = 0; i < nums.length; i++) {
                if (nums[i] != i + 1) {
                    return i + 1;
                }
            }
            return i + 1;
        }
    
    • PHP
        /**
         * firstMissingPositive2
         * @param $nums
         * @return int
         */
        function firstMissingPositive2($nums) {
            $n = count($nums);
            for ($i = 0; $i < $n; $i++) {
                while ($nums[$i] > 0 && $nums[$i] <= $n && $nums[$nums[$i] - 1] != $nums[$i]) {
                    $idx        = $nums[$i] - 1;
                    $tmp        = $nums[$i];
                    $nums[$i]   = $nums[$idx];
                    $nums[$idx] = $tmp;
                }
            }
    
            for ($i = 0; $i < $n; $i++) {
                if ($nums[$i] != $i + 1) {
                    return $i + 1;
                }
            }
            return $n + 1;
        }
    

    相关文章

      网友评论

          本文标题:FirstMissingPositive

          本文链接:https://www.haomeiwen.com/subject/xjqxgqtx.html