leetcode 645. Set Mismatch
来源:互联网 发布:域名主机购买多少钱 编辑:程序博客网 时间:2024/06/02 02:50
1.题目
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.
翻译: 给一个数组S 包含从1到n的数,由于数据错误,导致其中一个数出现两次,一个数没有出现。
找出这两个数。
Example 1:
Input: nums = [1,2,2,4]
Output: [2,3]
2.分析
不开辟额外空间的话,可以在原数组上进行操作。
遍历一遍数组S,对与每个出现的数字i,把下标为i-1的数*(-1)
每次先判断对应下标的数是否为正数,如果为负数,说明当前的数字重复。
最后,整个数组中唯一的正数对应的下标 i+1 即为没有出现的数字。
3.代码
class Solution {public: vector<int> findErrorNums(vector<int>& nums) { int duplicate = 0; int missing = 0; for (int i = 0; i < nums.size(); i++) { nums[abs(nums[i]) - 1] *= -1; if (nums[abs(nums[i]) - 1] < 0)//出现两次,负负得正 duplicate = abs(nums[i]); else nums[abs(nums[i]) - 1] *= -1; } for (int i = 0; i < nums.size(); i++) { if (nums[i] > 0) { missing = i + 1; break; } } return vector<int>{duplicate, missing}; }};
阅读全文
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 【思维查找】
- PAT 1068. Find More Coins (30) DFS,01背包
- toolbar详解
- bootstrapValidator表单验证使用方法
- Python爬虫框架Scrapy学习三记—让虫子爬
- CSDN Markdown编辑器写博客
- leetcode 645. Set Mismatch
- 【MVP+retrofit+rxAndroid+dagger2】读易读应用框架笔记(三)完结篇
- oracle逻辑备份和恢复
- 写在成年之际--年度总结
- Centos下安装Python3.5.1
- Javaweb之JSP入门
- 9-3(线段树维护最大最小值)
- iOS学习笔记-107.多线程06——CGD线程间通信下载图片
- how are you