leetcode 645. Set Mismatch
来源:互联网 发布:主升浪起爆点公式源码 编辑:程序博客网 时间:2024/06/02 03:35
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.
本题题意很简单就是寻找一个缺失元素和一个重复元素,最直接的方法就是直接统计即可,但是发现了一个有意思的方法:它是通过做交换把存在的值交换到对应的位置,然后做一次统计
代码如下:
#include <iostream>#include <vector>#include <map>#include <set>#include <queue>#include <stack>#include <string>#include <climits>#include <algorithm>#include <sstream>#include <functional>#include <bitset>#include <numeric>#include <cmath>#include <regex>using namespace std;class Solution {public: vector<int> findErrorNums(vector<int>& nums) { for (int i = 0; i<nums.size(); i++) { while (nums[i] != nums[nums[i] - 1]) swap(nums[i], nums[nums[i] - 1]); } for (int i = 0; i<nums.size(); i++) { if (nums[i] != i + 1) return{ nums[i], i + 1 }; } } vector<int> findErrorNumsByLoop(vector<int>& nums) { vector<int> res(2, 0), cnt(nums.size(), 0); for (int num : nums) ++cnt[num - 1]; for (int i = 0; i < cnt.size(); ++i) { if (cnt[i] == 2) res[0] = i + 1; else if (cnt[i] == 0) res[1] = i + 1; } return res; }};
阅读全文
0 0
- leetcode 645. Set Mismatch
- [LeetCode]645. Set Mismatch
- 【LeetCode】645. Set Mismatch
- LeetCode 645. Set Mismatch
- leetcode 645. Set Mismatch
- [LeetCode]645. Set Mismatch
- leetcode 645. Set Mismatch
- Leetcode 645. Set Mismatch 找缺值 解题报告
- LeetCode 645 Set Mismatch
- Leetcode 645 Set Mismatch
- leetcode--645--Set Mismatch
- 645. Set Mismatch
- 645. Set Mismatch
- 645. Set Mismatch
- 645. Set Mismatch
- 645. Set Mismatch
- 645. Set Mismatch
- 2017.12.25 LeetCode 645. Set Mismatch 【思维查找】
- Unity 生命周期
- python基础数据类型二
- ES6 let和var的四个不同
- 重识java1
- 并查集模板
- leetcode 645. Set Mismatch
- 第一节 安装Matlab 2016a Win64
- 马化腾、李彦宏、雷军,程序员国服三强谁的编程能力最牛?
- pandas字符串匹配
- SSM
- CodeForces
- 鲁班节点2017v1.0.0官方版下载附安装教程
- 【清华集训2017模拟12.10】回文串(回文树+树链剖分)
- spring aop学习记录