【LeetCode】448. Find All Numbers Disappeared in an Array(找到数组中消失的元素)
题目链接:https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/description/
难度:Easy
题目描述:
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]
解释:长度为n的数组,里面每个元素1=<a[i]<=n,找到1-n中里面没有出现的。要求:不能用额外的空间,时间复杂度O(n)。
思路:遍历数组,遇到一个大于零的,就把它在数组中所对应的元素取相反数,遍历完成后仍然大于0的元素的下标即为消失的元素。
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
int n=nums.length;
for(int i=0;i<n;i++)
{
int ab=Math.abs(nums[i])-1;
if(nums[ab]<0)
{
continue;
}
else {
nums[ab]=-nums[ab];
}
}
List<Integer>list=new ArrayList<Integer>();
for(int i=0;i<n;i++)
{
if(nums[i]>0)
list.add(i+1);
}
return list;
}
}
日期:2018/2/24-12:48