日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

每天一道LeetCode-----删除序列中指定元素,将满足要求的元素移动到前面

發(fā)布時間:2024/4/19 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 每天一道LeetCode-----删除序列中指定元素,将满足要求的元素移动到前面 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

Move Zeroes

原題鏈接Move Zeroes

意思是給定一個數(shù)組,將所有的0都移到后面,不能改變非0元素的相對順序
把非0元素移到前面,后面補零即可,比較簡單

class Solution { public:void moveZeroes(vector<int>& nums) {if(nums.size() == 0)return;/* 記錄上一個為0的位置,把下一次遇到的非0元素放到這個位置,然后后移一位,繼續(xù)尋找非0元素 */int prv_idx = 0;for(auto n : nums){if(n != 0)nums[prv_idx++] = n;}/* prv_idx此時的值就是非0元素的個數(shù),把剩下的位置都補0 */for(int i = prv_idx; i < nums.size(); ++i)nums[i] = 0;} };

Remove Element

原題鏈接Remove Element

意思是給定數(shù)組,將所有不為給定數(shù)值的元素移到前面,不能改變這些元素的相對順序,返回與給定數(shù)值不相等的元素個數(shù)。和上面的一樣,0換成參數(shù)而已,而且不需要補全…

class Solution { public:int removeElement(vector<int>& nums, int val) {if(nums.size() == 0)return 0;int prv_idx = 0;for(auto n : nums){if(n != val)nums[prv_idx++] = n;}return prv_idx;} };

Remove Duplicates from Sorted Array

原題鏈接Remove Duplicates from Sorted Array

意思是給定有序數(shù)組,相同的元素值留一個,基準值不固定,和上面的題有點不同,但思路一樣

class Solution { public:int removeDuplicates(vector<int>& nums) {if(nums.size() == 0)return 0;/* 記錄上一個找到的元素的位置,現(xiàn)在要找的元素不能和上一個元素相同 */int prv_idx = 0;for(int i = 1; i < nums.size(); ++i){if(nums[i] != nums[prv_idx])nums[++prv_idx] = nums[i];}return prv_idx + 1;} };

Remove Linked List Elements

原題鏈接Remove Linked List Elements

意思是給定鏈表,刪除指定數(shù)值的節(jié)點,比較簡單,遍歷一遍即可

/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*/ class Solution { public:ListNode* removeElements(ListNode* head, int val) {if(!head)return nullptr;ListNode* header = new ListNode(-1);header->next = head;ListNode* cur = head;ListNode* prv = header;while(cur){if(cur->val == val)prv->next = cur->next;elseprv = cur; cur = cur->next;}ListNode* res = header->next;delete header;return res;} };

總結

以上是生活随笔為你收集整理的每天一道LeetCode-----删除序列中指定元素,将满足要求的元素移动到前面的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。