leetcode 448. Find All Numbers Disappeared in an Array
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]
AC:(用了额外空间)
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int* findDisappearedNumbers(int* nums, int numsSize, int* returnSize) {
int* result=(int*)malloc(numsSize*sizeof(int));
int* result_real=(int*)malloc((numsSize/2+1)*sizeof(int));
int length=0;
for(int i=0;i<numsSize;i++)
{
result[nums[i]-1]=1;
}
for(int i=0;i<numsSize;i++)
{
if(result[i]!=1)
{
result_real[length]=i+1;
length++;
}
}
*returnSize=length;
return result_real;
}
AC:(改进)
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int* findDisappearedNumbers(int* nums, int numsSize, int* returnSize) {
int* result=(int*)malloc(numsSize*sizeof(int));
int length=0;
for(int i=0;i<numsSize;i++)
{
int m=abs(nums[i])-1;
if(nums[m]>0)
{
nums[m]=-nums[m];
}
}
for(int i=0;i<numsSize;i++)
{
if(nums[i]>0)
{
result[length]=i+1;
length++;
}
}
*returnSize=length;
return result;
}