☰
【leetcode】Leetcode:448. Find All Numbers Disappeared in an Array
2026/10/23 1:02:15 网站建设 项目流程

问题描述:
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]

难度等级:简单

这个有点小技巧,就是设置index,然后对应数字设成负的,最后只要看对应index的数是正数的,取出对应的index就好了O(∩_∩)O哈哈~

class Solution { public: vector<int> findDisappearedNumbers(vector<int>& nums) { for(auto num:nums){ int index = num>0 ? num:-num; index--; if(nums[index]>0){ nums[index] = -nums[index]; } } vector<int> result; for(int i = 0; i < nums.size(); i++){ if(nums[i]>0){ result.push_back(i+1); } } return result; } };

恩恩O(∩_∩)O哈哈~

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询