欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

查找数组中未出现的和出现2次的数值 Set Mismatch

发布时间:2025/3/19 编程问答 52 豆豆
生活随笔 收集整理的这篇文章主要介绍了 查找数组中未出现的和出现2次的数值 Set Mismatch 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

为什么80%的码农都做不了架构师?>>>   

问题:

The 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]

Note:

  • The given array size will in the range [2, 10000].
  • The given array's numbers won't have any order.
  • 解决:

    ①  使用一个标记数组标记每个值是否出现过,若存在重复,则将重复的值加入到结果中;再遍历一次数组,得到唯一一个未标记的值,就是缺失的值。

    public class Solution { // 7ms
        public int[] findErrorNums(int[] nums) {
            int res[] = new int[2];
            boolean[] isOcc= new boolean[nums.length + 1];
            for (int i = 0;i < nums.length ;i ++ ) {
                if(isOcc[nums[i]]) res[0] = nums[i];//该数值已经出现过
                else isOcc[nums[i]] = true;
            }
            for (int i = 1;i <= nums.length ;i ++ ) {
                if(! isOcc[i]) res[1] = i; //i 没出现过
            }
            return res;
        }
    }

    转载于:https://my.oschina.net/liyurong/blog/1510776

    总结

    以上是生活随笔为你收集整理的查找数组中未出现的和出现2次的数值 Set Mismatch的全部内容,希望文章能够帮你解决所遇到的问题。

    如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。