国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 學(xué)院 > 開(kāi)發(fā)設(shè)計(jì) > 正文

448.Find All Numbers Disappeared in an Array

2019-11-06 06:25:28
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

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]

Subscribe to see which companies asked this question.

first answer(using two loop) wrong reason: time limit exceeded

class Solution {public: vector<int> findDisappearedNumbers(vector<int>& nums) { int s = nums.size(); vector<int> out; for (int i = 1; i <= s; i++) { out.push_back(i); } int in = 0; for (int j = 0; j < s; j++) { if (nums[j] == i) in++; } if (in == 0) { out.push_back(i); } return out; }};

correct answer:

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

analyse: to avoid using extra space,use the sign symbol of position as the mark to existance.


發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 昂仁县| 博乐市| 馆陶县| 临潭县| 北安市| 阜新市| 桂阳县| 枣强县| 克山县| 南部县| 石屏县| 呈贡县| 达拉特旗| 开化县| 扎鲁特旗| 东源县| 满洲里市| 定西市| 古田县| 乳山市| 邵阳县| 邹城市| 子长县| 高阳县| 建湖县| 若尔盖县| 潮安县| 鄂州市| 屏山县| 中卫市| 灌南县| 盐边县| 富宁县| 称多县| 淮阳县| 镶黄旗| 永康市| 闽侯县| 临高县| 科尔| 磴口县|