645. Set Mismatch

class Solution {
public:
    vector<int> findErrorNums(vector<int>& nums) {
       
        int a=nums.size();
        vector<int> res;
        for(int i=0;i<a;i++)
        {
            
       
             for(int j=i+1;j<a;j++)
        {
                 if(nums[i]==nums[j])
                 {   res.push_back(nums[i]);
                 res.push_back(nums[i]+1);
                 }
        }
        }
         return res;
    }
};

题目:


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:

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

题目链接


题意:

有一个1-n的集合,之后数据出错导致一个数复制到另一个位置上,导致这个集合中有一个数出现了2次,有一个数出现了0次。

题目和 LeetCode 448 Find All Numbers Disappeared in an Array非常相似,采用的解题方法也几乎是同一种,都是利用了把数当作下标来使用,利用负数做标记的方法,实现出现一次,和出现0次的区分。


代码如下:

[cpp]   view plain  copy
 print ?
  1. class Solution {  
  2. public:  
  3.     vector<int> findErrorNums(vector<int>& nums) {  
  4.         vector <int> ans;  
  5.         for (int i = 0; i < nums.size(); i++) {  
  6.             int index = abs(nums[i]) - 1;  
  7.             if (nums[index] > 0) {  
  8.                 nums[index] *= -1;  
  9.             }  
  10.             else {  
  11.                 ans.push_back(index + 1);  
  12.             }  
  13.         }  
  14.         for (int i = 0; i < nums.size(); i++) {  
  15.             if (nums[i] > 0) {  
  16.                 ans.push_back(i + 1);  
  17.             }  
  18.         }  
  19.         return ans;  
  20.     }  
  21. };  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值