Given an array and a value, remove all instances of that value in place and return the new length.
The order of elements can be changed. It doesn‘t matter what you leave beyond the new length.
Solution 1: 设置一个新的下标length,遍历过程中遇到val就跳过,否则就赋给新数组下标对应元素。缺点是有多余的赋值。
1 class Solution { 2 public: 3 int removeElement(vector<int>& nums, int val) { 4 if(nums.empty())return 0; 5 int length=0; 6 for(int i=0;i<nums.size();i++){ 7 if(nums[i]!=val) 8 nums[length++]=nums[i]; 9 else 10 continue; 11 } 12 return length; 13 } 14 };
Solution 2:最优美的解法,当遍历过程中遇到val,就用末尾的元素来填补。这样甚至遍历不到一次。注意:从末尾换过来的可能仍然是elem,因此i--,需要再次判断。
1 class Solution { 2 public: 3 int removeElement(vector<int>& nums, int val) { 4 int newlength = nums.size(); 5 for(int i = 0; i < newlength; i ++) 6 { 7 if(nums[i] == val){ 8 nums[i] = nums[newlength-1]; 9 i--; 10 newlength--; 11 } 12 } 13 return newlength; 14 } 15 };
时间: 2024-10-05 23:22:51