查找数组中未出现的和出现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的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 大型网站运维工程师的职责和前景
- 下一篇: JavaScript设置对象的不可拓展