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; } }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://specialneedsforspecialkids.com/yun/71658.html
摘要:先想到的是,其實(shí)也可以,只是需要在遍歷的時候,添加到數(shù)組中的數(shù)要掉,略微麻煩了一點(diǎn)。在里跑的時候,也要快一點(diǎn)。另一種類似做法的就快的多了。如果是找出所有包括重復(fù)的截距呢 Problem Given two arrays, write a function to compute their intersection. Notice Each element in the result m...
摘要:整個過程相當(dāng)于,直接在和里去掉既是又是的。所以最后返回的,一定是只出現(xiàn)過一次的,而出現(xiàn)兩次的都在里,出現(xiàn)三次的都被消去了。 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 ...
摘要:把矩陣所有零點(diǎn)的行和列都置零,要求不要額外的空間。對于首行和首列的零點(diǎn),進(jìn)行額外的標(biāo)記即可。這道題我自己做了四遍,下面幾個問題需要格外注意標(biāo)記首行和首列時,從到遍歷時,若有零點(diǎn),則首列標(biāo)記為從到遍歷,若有零點(diǎn),則首行標(biāo)記為。 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...
閱讀 1961·2021-11-23 09:51
閱讀 873·2021-11-19 09:40
閱讀 829·2021-10-27 14:20
閱讀 5004·2021-10-09 09:52
閱讀 3297·2021-10-09 09:44
閱讀 1729·2021-10-08 10:05
閱讀 5053·2021-09-09 11:47
閱讀 3481·2019-08-30 12:47