用 C++ 查詢陣列中的所有重複項


假設我們有一個整數陣列,範圍是 1 ≤ a[i] ≤ n(n = 陣列的大小),其中一些元素出現兩次,而另一些元素只出現一次。我們必須找出在此陣列中出現兩次的所有元素。所以,如果陣列是 [4,3,2,7,8,2,3,1],則輸出將是 [2, 3]

為解決這個問題,我們將按照以下步驟操作:

  • n := 陣列大小,建立一個名為 ans 的陣列
  • 對於 0 到 n – 1 範圍內的 i
    • x := nums[i] 的絕對值
    • x 減去 1
    • 如果 nums[x] < 0,則將 x + 1 新增到 ans 中,否則 nums[x] := nums[x] * (-1)
  • 返回 ans

示例(C++)

讓我們看看以下實現以加深理解:

即時演示

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
class Solution {
public:
   vector<int> findDuplicates(vector<int>& nums) {
      int n = nums.size();
      vector <int> ans;
      for(int i = 0; i < n; i++){
         int x = abs(nums[i]);
         x--;
         if(nums[x] < 0) ans.push_back(x + 1);
         else nums[x] *= -1;
      }
      return ans;
   }
};
main(){
   Solution ob;
   vector<int> v = {4,3,2,7,8,2,3,1};
   print_vector(ob.findDuplicates(v));
}

輸入

[4,3,2,7,8,2,3,1]

輸出

[2,3]

更新於:2020 年 4 月 28 日

1.1 萬次瀏覽

開啟你的 職業

完成此課程以獲得認證

開始
廣告
© . All rights reserved.