leetCode刷题记录74_645_Set Mismatch

/*****************************************************问题描述*************************************************
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.
给定有n个整数的数组,本来应当含有从1到n,现在有2个元素重复了,丢失了1个数,找到这个重复的元素和丢失的那个元素
/*****************************************************我的解答*************************************************
/**
 * @param {number[]} nums
 * @return {number[]}
 */
var findErrorNums = function(nums) {
    nums.sort((a,b) => {return a - b});
    var dup = 0;
    var missing = 0;
    var retArray = [];
    for(var index = 0; index < nums.length; index++)
    {
        if(nums[index] == nums[index + 1])
        {
            dup = nums[index];
            nums.splice(index,1);
            break;
        }    
    }    
    for(var index = 0; index <= nums.length; index++)
    {
        if(nums[index] != index + 1)
        {
            missing = index + 1;
            break;
        }    
    }    
    retArray.push(dup);
    retArray.push(missing);
    return retArray;
};
console.log(findErrorNums([1,1]));
 

发布了135 篇原创文章 · 获赞 10 · 访问量 6245

猜你喜欢

转载自blog.csdn.net/gunsmoke/article/details/89092832
今日推荐