zoukankan      html  css  js  c++  java
  • 645. Set Mismatch挑出不匹配的元素和应该真正存在的元素

    [抄题]:

    he set S originally contains numbers from 1 to n. But unfortunately, due to the data error, one of the numbers in the set got duplicated to another number in the set, which results in repetition of one number and loss of another number.

    Given an array nums representing the data status of this set after the error. Your task is to firstly find the number occurs twice and then find the number that is missing. Return them in the form of an array.

    Example 1:

    Input: nums = [1,2,2,4]
    Output: [2,3]

     [暴力解法]:

    hashset

    时间分析:

    空间分析:n

     [优化后]:

    时间分析:

    空间分析:1

    [奇葩输出条件]:

    [奇葩corner case]:

    1. 把数字1对应到nums[0],为了不出现溢出,需要-1

    [思维问题]:

    [一句话思路]:

    为了优化空间,判断重复性时 直接*(-1

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

    [一刷]:

    1. 循环中先写退出条件,再写正常条件

    [二刷]:

    1. 标记元素为负数之后,记得需要变回正数才能正常返回

    [三刷]:

    [四刷]:

    [五刷]:

      [五分钟肉眼debug的结果]:

    [总结]:

    为了优化空间,判断重复性时 直接*(-1)

    [复杂度]:Time complexity: O(n) Space complexity: O(1)

    [英文数据结构或算法,为什么不用别的数据结构或算法]:

    [关键模板化代码]:

    //for loop, * (-1), res[0]
            for (int num : nums) {
                if (nums[Math.abs(num) - 1] < 0) {
                    res[0] = Math.abs(num);
                }else {
                    nums[Math.abs(num) - 1] *= (-1);
                }
            }

    [其他解法]:

    [Follow Up]:

    [LC给出的题目变变变]:

    287. Find the Duplicate Number 快慢指针可以找重复?不是找中点么

     [代码风格] :

    class Solution {
        public int[] findErrorNums(int[] nums) {
            //ini
            int[] res = new int[2];
            
            //cc
            if (nums == null || nums.length == 0) {
                return res;
            }
            
            //for loop, * (-1), res[0]
            for (int num : nums) {
                if (nums[Math.abs(num) - 1] < 0) {
                    res[0] = Math.abs(num);
                }else {
                    nums[Math.abs(num) - 1] *= (-1);
                }
            }
            
            //find res[1]
            for (int i = 0; i < nums.length; i++) {
                if (nums[i] > 0) {
                    res[1] = i + 1;
                }
            }
            
            //return 
            return res;
        }
    }
    View Code
  • 相关阅读:
    Indy10 系列(一)——获取最新的Indy源码
    Oracle9i中关于select into的执行过程 (转)
    Oracle创建删除用户、角色、表空间、导入导出数据库命令行方式总结(转)
    手动创建Oracle 11g数据库(转载)
    Indy10 系列(四)——编译Indy源码
    Indy10 系列(二)——获取最新的Indy源码
    Delphi 2010手动安装indy10.5.7
    Indy10 系列(三)——获取最新的Indy源码
    Indy10 系列(五)——安装Indy控件,重新编译Lazarus
    Unix文化RTFM
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8947574.html
Copyright © 2011-2022 走看看