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

首頁 > 學院 > 開發(fā)設計 > 正文

leecode 解題總結(jié):27 Remove Element

2019-11-14 12:30:21
字體:
供稿:網(wǎng)友
#include <iostream>#include <stdio.h>#include <vector>#include <algorithm>using namespace std;/*問題:Given an array and a value, remove all instances of that value in place and return the new length.Do not allocate extra space for another array, you must do this in place with constant memory.The order of elements can be changed. It doesn't matter what you leave beyond the new length.Example:Given input array nums = [3,2,2,3], val = 3Your function should return length = 2, with the first two elements of nums being 2.分析:此題實際上就是刪除元素為指定值的元素,數(shù)組事先是無序的。一種簡單方法是:先排序,排序結(jié)束后通過二分查找元素上下區(qū)間,刪除區(qū)間內(nèi)元素,時間復雜度為O(N*logN)如果不排序,刪除指定元素,每次從前向后移動,找到指定元素后,將該元素后面所有元素向前移動一位,遍歷元素的時間復雜度為O(N),找到元素后,后面所有元素向前移動時間復雜度為O(N),總的時間復雜度為O(N*N)lower_bound:查找元素第一個出現(xiàn)的位置,或者如果沒有該元素,查找大于該元素的位置,使得將元素插入數(shù)組后數(shù)組仍然有序upper_bound:查找大于元素x的第一個位置,使得如果將待查找元素插入在該位置后,該數(shù)組仍然有序輸入:4(元素個數(shù)) 3(待刪除元素)3 2 2 3(所有數(shù)組元素)4 13 2 2 3輸出:2(新數(shù)組的長度)4*/void PRint(vector<int>& nums){if(nums.empty()){cout << "nums is empty" << endl;return ;}int length = nums.size();for(int i = 0 ; i < length ; i++){cout << nums.at(i) << " ";}cout << endl;}class Solution {public:    int removeElement(vector<int>& nums, int val) {if(nums.empty()){return 0;}//排序sort(nums.begin() , nums.end());//查找>=元素的第一個出現(xiàn)的位置,位置是迭代器vector<int>::iterator low = lower_bound(nums.begin() , nums.end() , val);//超找>元素第一個出現(xiàn)的位置vector<int>::iterator high = upper_bound(nums.begin() , nums.end() , val);//刪除元素nums.erase(low , high);int length = nums.size();//print(nums);return length;    }};void process(){int num;vector<int> datas;int value;int delVal;while(cin >> num >> delVal){datas.clear();for(int i = 0 ; i < num ; i++){cin >> value;datas.push_back(value);}Solution solution;int result = solution.removeElement(datas , delVal);cout << result << endl;}}int main(int argc , char* argv[]){process();getchar();return 0;}
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 新竹县| 仁化县| 丰原市| 乌兰县| 松原市| 中超| 青铜峡市| 瑞安市| 永年县| 武陟县| 乌兰察布市| 泉州市| 泗阳县| 西藏| 潜江市| 巴彦县| 祁阳县| 疏勒县| 大石桥市| 尉氏县| 余干县| 沂源县| 新干县| 烟台市| 高碑店市| 鹿泉市| 淅川县| 牡丹江市| 宁海县| 九龙坡区| 濉溪县| 泾川县| 鹤岗市| 禹州市| 信阳市| 西峡县| 潼关县| 金川县| 惠来县| 通河县| 桂阳县|