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
  • 相关阅读:
    自己动手写RTP服务器——传输所有格式的视频
    自己动手写RTP服务器——用RTP协议传输TS流
    自己动手写RTP服务器——关于RTP协议
    P2P直播、点播技术学习经验
    开源网络通信库参考
    小明历险记:规则引擎drools教程一
    Drools规则引擎入门指南(一)
    drools规则引擎初探
    《高性能MySQL》笔记-BLOB与TEXT
    业务系统上下游数据一致性检测系统(类似对账系统)
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8947574.html
Copyright © 2011-2022 走看看