bl双性强迫侵犯h_国产在线观看人成激情视频_蜜芽188_被诱拐的少孩全彩啪啪漫画

C++有序數組中去除重復項的方法

這篇文章主要講解了“C++有序數組中去除重復項的方法”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“C++有序數組中去除重復項的方法”吧!

成都創新互聯從2013年成立,是專業互聯網技術服務公司,擁有項目成都網站設計、網站制作網站策劃,項目實施與項目整合能力。我們以讓每一個夢想脫穎而出為使命,1280元懷遠做網站,已為上家服務,為懷遠各地企業和個人服務,聯系電話:18982081108

有序數組中去除重復項

Example 1:

Given nums = [1,1,1,2,2,3],

Your function should return length =

5

, with the first five elements of

nums

being

1, 1, 2, 2

and 3 respectively.

It doesn"t matter what you leave beyond the returned length.

Example 2:

Given nums = [0,0,1,1,1,1,2,3,3],

Your function should return length =

7

, with the first seven elements of

nums

being modified to 

0

, 0, 1, 1, 2, 3 and 3 respectively.

It doesn"t matter what values are set beyond the returned length.

Clarification:

Confused why the returned value is an integer but your answer is an array?

Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.

Internally you can think of this:

// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);

// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
print(nums[i]);
}

這道題是之前那道 Remove Duplicates from Sorted Array 的拓展,這里允許最多重復的次數是兩次,那么可以用一個變量 cnt 來記錄還允許有幾次重復,cnt 初始化為1,如果出現過一次重復,則 cnt 遞減1,那么下次再出現重復,快指針直接前進一步,如果這時候不是重復的,則 cnt 恢復1,由于整個數組是有序的,所以一旦出現不重復的數,則一定比這個數大,此數之后不會再有重復項。理清了上面的思路,則代碼很好寫了:

解法一:

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int pre = 0, cur = 1, cnt = 1, n = nums.size();
        while (cur < n) {
            if (nums[pre] == nums[cur] && cnt == 0) ++cur;
            else {
                if (nums[pre] == nums[cur]) --cnt;
                else cnt = 1;
                nums[++pre] = nums[cur++];
            }
        }
        return nums.empty() ? 0 : pre + 1;
    }
};

這里其實也可以用類似于 Remove Duplicates from Sorted Array 中的解法三的模版,由于這里最多允許兩次重復,那么當前的數字 num 只要跟上上個覆蓋位置的數字 nusm[i-2] 比較,若 num 較大,則絕不會出現第三個重復數字(前提是數組是有序的),這樣的話根本不需要管 nums[i-1] 是否重復,只要將重復個數控制在2個以內就可以了,參見代碼如下:

解法二:

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int i = 0;
        for (int num : nums) {
            if (i < 2 || num > nums[i - 2]) {
                nums[i++] = num;
            }
        }
        return i;
    }
};

感謝各位的閱讀,以上就是“C++有序數組中去除重復項的方法”的內容了,經過本文的學習后,相信大家對C++有序數組中去除重復項的方法這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是創新互聯,小編將為大家推送更多相關知識點的文章,歡迎關注!

新聞名稱:C++有序數組中去除重復項的方法
標題網址:http://vcdvsql.cn/article44/gjoshe.html

成都網站建設公司_創新互聯,為您提供營銷型網站建設品牌網站制作GoogleApp設計企業建站網站排名

廣告

聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯

成都定制網站建設