Code10は要素を削除します

トピック

leetcode27。要素の削除numsの
配列とvalの値を指定します。値がvalと等しいすべての要素を削除し、削除された配列の新しい長さを返す必要があります。
余分な配列スペースを使用しないでください。O(1)の余分なスペースのみを使用し、入力配列をその場で変更する必要があります。
要素の順序は変更できます。新しい長さを超える配列内の要素を考慮する必要はありません。

例1:
nums = [3,2,2,3]、val = 3の場合、
関数は新しい長さ2を返す必要があり、numsの最初の2つの要素は両方とも2です。
新しい長さを超える配列内の要素を考慮する必要はありません。

例2:
nums = [0,1,2,2,3,0,4,2]、val = 2の場合、
関数は新しい長さ5を返す必要があり、numsの最初の5つの要素は0、1です。 3、0、4。
これらの5つの要素は任意の順序にすることができることに注意してください。
新しい長さを超える配列内の要素を考慮する必要はありません。

コード

// C
int removeElement(int* nums, int numsSize, int val) {
    
    
  int i = 0;
  for(int j = 0; j < numsSize; ++j){
    
    
    if (nums[j] != val){
    
    
      nums[i] = nums[j];
      ++i;
    }
  }
  return i;
}
// C++
#include <vector>
using namespace std;
class Solution {
    
    
 public:
  int removeElement(vector<int>& nums, int val) {
    
    
    auto it = nums.begin();
    while(it != nums.end()) {
    
    
      if (*it == val) {
    
    
        it = nums.erase(it);
      }else{
    
    
        ++it;
      }
    }
    return nums.size();
  }
};

ここに画像の説明を挿入

テスト

#include <iostream>

void print(const vector<int>& nums) {
    
    
  cout << "nums : ";
  for (auto& i : nums) {
    
    
    cout << i << " ";
  }
  cout << std::endl;
}

void print(int* nums, int numsSize) {
    
    
  cout << "nums : ";
  for (int j = 0; j < numsSize; ++j) {
    
    
    cout << nums[j] << " ";
  }
  cout << std::endl;
}

int main() {
    
    
  {
    
    
    // C
    int nums[] = {
    
    2, 2, 3, 4, 5, 5, 6, 7};
    int n = sizeof(nums) / sizeof(nums[0]);
    print(nums, n);
    removeElement(nums, n, 5);
    print(nums, n);
  }
  {
    
    
    // C++
    std::vector<int> vc = {
    
    2, 2, 3, 4, 5, 5, 6, 7};
    print(vc);
    Solution s;
    s.removeElement(vc, 5);
    print(vc);
  }
  std::cin.get();
  return 0;
}
  • 結果
nums : 2 2 3 4 5 5 6 7
nums : 2 2 3 4 6 7 6 7 // 打印的原长度所有元素
nums : 2 2 3 4 5 5 6 7
nums : 2 2 3 4 6 7

おすすめ

転載: blog.csdn.net/luoshabugui/article/details/109504157