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
  • 相关阅读:
    SDNU 1219.sign up problem
    SDNU 1232.A*B Problem(高精度)
    Go操作MySQL
    BootStrap jQuery 在线cdn
    Go语言标准库之http/template
    Go语言基础之net/http
    Go语言基础之网络编程
    Go语言基础之单元测试
    Go语言基础之rand(随机数)包
    Go语言基础之并发
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8947574.html
Copyright © 2011-2022 走看看