查找数组中未出现的和出现2次的数值 Set Mismatch
为什么80%的码农都做不了架构师?>>>
问题:
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:
解决:
① 使用一个标记数组标记每个值是否出现过,若存在重复,则将重复的值加入到结果中;再遍历一次数组,得到唯一一个未标记的值,就是缺失的值。
public class Solution { // 7ms
public int[] findErrorNums(int[] nums) {
int res[] = new int[2];
boolean[] isOcc= new boolean[nums.length + 1];
for (int i = 0;i < nums.length ;i ++ ) {
if(isOcc[nums[i]]) res[0] = nums[i];//该数值已经出现过
else isOcc[nums[i]] = true;
}
for (int i = 1;i <= nums.length ;i ++ ) {
if(! isOcc[i]) res[1] = i; //i 没出现过
}
return res;
}
}
转载于:https://my.oschina.net/liyurong/blog/1510776
总结
以上是生活随笔为你收集整理的查找数组中未出现的和出现2次的数值 Set Mismatch的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 大型网站运维工程师的职责和前景
- 下一篇: 后台获取html控件的值