LeetCode-Set Mismatch

Description:
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.

题意:给定一个数组,包含元素[1,n],其中仅有一个元素出现两次,一个元素出现0次,要求找出出现两次和出现0次的元素;

解法:既然已经说明了数组中的元素是在范围[1,n]内的,那么我们可以对数组中元素对应的下标进行标记,例如对于元素2,我们标记数组下标位置1处,表明元素2出现过,这里因为元素都是正数,因此,我们令元素取负来标记;
举个例子:
给定数组arr = [4,2,2,1]

  • 对于第一个元素1,为了标记他,我们令arr[Math.abs(arr[0]) - 1] *= -1(即arr[3] = -1),得到arr = [4,2,2,-1]
  • 对于第二个元素2,令arr[Math.abs(arr[1] - 1) *= -1(即arr[1] = -2),得到arr = [4,-2,2,-1]
  • 对于第三个元素,因为arr[Math.abs(arr[2] - 1) < 0,说明这个元素出现了两次
  • 对于第四个元素,令arr[Math.abs(arr[3]) - 1) *= -1(即arr[0] = -4),得到arr = [-4,-2,2,-1]

我们最后再遍历得到的数组,数组中为正数的那个所在的位置,说明那个元素没有出现过,即元素3;

Java
class Solution {
    public int[] findErrorNums(int[] nums) {
        int twiceNum = -1;
        int misNum = -1;
        for (int i = 0; i < nums.length; i++) {
            if (nums[Math.abs(nums[i]) - 1] < 0) {
                twiceNum = Math.abs(nums[i]);    
            } else {
                nums[Math.abs(nums[i]) - 1] *= -1;    
            }
        }
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] > 0) {
                misNum = i + 1;
                break;
            } 
        }
        return new int[] {twiceNum, misNum};
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值