【LeetCode】448.Find All Numbers Disappeared in an Array(Easy)解题报告
2017-06-02 21:00
447 查看
【LeetCode】448.Find All Numbers Disappeared in an Array(Easy)解题报告
tags: Array
题目地址:https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/#/description
题目描述:
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.
Examples:
Input:
[4,3,2,7,8,2,3,1]
Output:
[5,6]
Solutions:
正解:
思想就是说比如nums数组有8个数,那么数组为nums[0]~nums[7],里面的数为1~8,数减一之后一定有下标对应,将对应下标的数取相反数,那么遍历之后正数的下标加一则为数组中未出现的数。
Date:2017年6月2日
tags: Array
题目地址:https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/#/description
题目描述:
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.
Examples:
Input:
[4,3,2,7,8,2,3,1]
Output:
[5,6]
Solutions:
正解:
//time : O(n) //space : O(n) public class Solution { public List<Integer> findDisappearedNumbers(int[] nums) { List<Integer> ret = new ArrayList<Integer>(); 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) { ret.add(i+1); } } return ret; } }
思想就是说比如nums数组有8个数,那么数组为nums[0]~nums[7],里面的数为1~8,数减一之后一定有下标对应,将对应下标的数取相反数,那么遍历之后正数的下标加一则为数组中未出现的数。
Date:2017年6月2日
相关文章推荐
- LeetCode解题报告 349. Intersection of Two Arrays [easy]
- 【LeetCode】104.Maximum Depth of Binary Tree(Easy)解题报告
- 【LeetCode】404.Sum of Left Leaves(Easy)解题报告
- 【LeetCode】572.Subtree of Another Tree(Easy)解题报告
- 【LeetCode】599.Minimum Index Sum of Two Lists(Easy)解题报告
- 【LeetCode】110. Balanced Binary Tree(Easy)解题报告
- LeetCode解题报告 110. Balanced Binary Tree [easy]
- LeetCode解题报告 257. Binary Tree Paths [easy]
- LeetCode解题报告 1. Two Sum[easy]
- LeetCode解题报告 70. Climbing Stairs [easy]
- LeetCode】101.Symmetric Tree(Easy)解题报告
- 【LeetCode】108.Convert Sorted Array to Binary Search Tree(Easy)解题报告
- LeetCode】66.Plus One(easy)解题报告
- 【LeetCode】112.Path Sum(Easy)解题报告
- 【LeetCode】617.Merge Two Binary Trees(Easy)解题报告
- LeetCode解题报告 104. Maximum Depth of Binary Tree [easy]
- 【LeetCode】628.Maximum Product of Three Numbers(Easy)解题报告
- 【LeetCode】160.Intersection of Two Linked Lists(Easy)解题报告
- 【LeetCode】226.Invert Binary Tree(Easy)解题报告
- 【LeetCode】637.Average of Levels in Binary Tree(Easy)解题报告