打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
448. Find All Numbers Disappeared in an Array

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]

解题思路:

参考了https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/481254/C++-solution-O(1)-Easy-7-lines-code

巧妙的改变数组本身的值。遍历整个数组,将数组的值作为索引,将对应索引位置的数组值变为负数,这样遍历一遍后,数组值为正的那个索引,比如nums[5] = 2, 则说明5没有出现过。在实际的应用中,如果数组的值可以随便改变,则可以使用此方法。

class Solution{public:    vector<int> findDisappearedNumbers(vector<int>& nums) {        vector<int> rlt;        for(int i=0; i<nums.size(); i  ) {            nums[abs(nums[i])-1] = -abs(nums[abs(nums[i])-1]);        }        for(int i=0; i<nums.size(); i  ) {            if(nums[i]>0) {                rlt.push_back(i 1);            }         }        return rlt;    }};

 

Haskei发布了153 篇原创文章 · 获赞 29 · 访问量 10万 私信 关注来源:https://www.icode9.com/content-4-625151.html
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
leetcode 448 Find All Numbers Disappeared in an Array   C++
​LeetCode刷题实战384:打乱数组
斯坦福CS231n深度学习课程笔记翻译(一)
Python中基础使用及Numpy、Scipy、Matplotlib 使用教程
单调栈 Monotonic Stack 的使用
C# 数据容器详解:Array、List、Dictionary、LinkedList、Queue、Stack
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服