Problem
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.
ExampleInput: nums = [1,2,2,4]
Output: [2,3]
public class Solution { /** * @param nums: an array * @return: the number occurs twice and the number that is missing */ public int[] findErrorNums(int[] nums) { // Write your code here int[] res = new int[2]; Setset = new HashSet<>(); Arrays.sort(nums); for (int i = 0; i < nums.length; i++) { if (set.contains(nums[i])) res[0] = nums[i]; else set.add(nums[i]); // put the commented for-loop here if (!set.contains(i+1)) res[1] = i+1; } // for (int i = 0; i < nums.length; i++) { // if (!set.contains(i+1)) { // res[1] = i+1; // break; // } // } return res; } }
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/71658.html
摘要:先想到的是,其实也可以,只是需要在遍历的时候,添加到数组中的数要掉,略微麻烦了一点。在里跑的时候,也要快一点。另一种类似做法的就快的多了。如果是找出所有包括重复的截距呢 Problem Given two arrays, write a function to compute their intersection. Notice Each element in the result m...
摘要:整个过程相当于,直接在和里去掉既是又是的。所以最后返回的,一定是只出现过一次的,而出现两次的都在里,出现三次的都被消去了。 Single Number I Problem Given 2*n + 1 numbers, every numbers occurs twice except one, find it. Example Given [1,2,2,1,3,4,3], return...
Problem Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at ...
摘要:把矩阵所有零点的行和列都置零,要求不要额外的空间。对于首行和首列的零点,进行额外的标记即可。这道题我自己做了四遍,下面几个问题需要格外注意标记首行和首列时,从到遍历时,若有零点,则首列标记为从到遍历,若有零点,则首行标记为。 Problem Given a m x n matrix, if an element is 0, set its entire row and column t...
Problem Given a string s and a dictionary of words dict, determine if s can be break into a space-separated sequence of one or more dictionary words. Example Given s = lintcode, dict = [lint, code]. R...
阅读 1979·2021-11-23 09:51
阅读 890·2021-11-19 09:40
阅读 840·2021-10-27 14:20
阅读 5039·2021-10-09 09:52
阅读 3313·2021-10-09 09:44
阅读 1741·2021-10-08 10:05
阅读 5116·2021-09-09 11:47
阅读 3493·2019-08-30 12:47