Problem
Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements of [1, n] inclusive that do not appear in this array.
Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.
Example:
Input: [4,3,2,7,8,2,3,1] Output: [5,6]Solution
class Solution { public ListfindDisappearedNumbers(int[] nums) { List res = new ArrayList<>(); for (int i = 0; i < nums.length; i++) { int val = Math.abs(nums[i])-1; if (nums[val] > 0) nums[val] = -nums[val]; } for (int i = 0; i < nums.length; i++) { if (nums[i] > 0) res.add(i+1); } return res; } }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://specialneedsforspecialkids.com/yun/72092.html
Problem Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. Find all the elements of [1, n] inclusive that do not appear in this array...
摘要:如果這個位置的值為正意味著我們還沒有對這個元素進行過操作,我們將這個位置的元素的值取負。在整個遍歷結(jié)束后,沒有取負的值的索引,就可以對應(yīng)到?jīng)]有在數(shù)組出現(xiàn)過的值解法 題目詳情 Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others ap...
摘要:題目要求假設(shè)一個長度為的整數(shù)數(shù)組,數(shù)組中的元素的值位于區(qū)間中。代碼如下但是這個實現(xiàn)違背了的空間復(fù)雜度這里結(jié)果集不視為額外空間。如果當(dāng)前元素?zé)o需進行交換,則指針右移一位。無需進行的場景是指當(dāng)前元素已經(jīng)出現(xiàn)在目標(biāo)位置上了。 題目要求 Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some element...
摘要:題目鏈接一般這種類型的題要,要么給賦值成不在范圍內(nèi)的數(shù),要么到對應(yīng)位置。 448. Find All Numbers Disappeared in an Array 題目鏈接:https://leetcode.com/problems... 一般這種類型的題要in place,要么給num[i]賦值成不在范圍內(nèi)的數(shù),要么swap到對應(yīng)位置。 public class Solution ...
摘要:題目鏈接題目分析給定一個到的數(shù)組,返回其中缺失的數(shù)字。思路用得出到的數(shù)字,再用和給定的數(shù)組計算差集。最終代碼若覺得本文章對你有用,歡迎用愛發(fā)電資助。 D79 448. Find All Numbers Disappeared in an Array 題目鏈接 448. Find All Numbers Disappeared in an Array 題目分析 給定一個1到n的數(shù)組,返回...
閱讀 1518·2021-11-18 10:02
閱讀 1657·2021-09-04 16:40
閱讀 3171·2021-09-01 10:48
閱讀 874·2019-08-30 15:55
閱讀 1853·2019-08-30 15:55
閱讀 1365·2019-08-30 13:05
閱讀 3013·2019-08-30 12:52
閱讀 1625·2019-08-30 11:24