The order of elements can be changed. It doesn't matter what you leave beyond the new length.
之前leet code有類似的題目
一個pointer去找val 另外一個去找非val的 在交換
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | int removeElement(int* nums, int numsSize, int val) { int Nonval=0,Isval=0; for(int i=0;i<numsSize;i++){ while(Isval<numsSize && nums[Isval]!=val)Isval++; //while(Nonval<numsSize && nums[Nonval]==val)Nonval++; Nonval=Isval; while(Nonval<numsSize && nums[Nonval]==val)Nonval++; if(Nonval>=numsSize)return Isval-1>=0? Isval:0; else{ int temp = nums[Nonval]; nums[Nonval]=nums[Isval]; nums[Isval]=temp; } Isval++; } } |
1 2 3 4 5 6 7 8 9 10 11 12 | int removeElement(int* nums, int numsSize, int val) { int remove = 0; for(int i = 0; i < numsSize; ++i) { if(nums[i] == val) ++remove; else nums[i - remove] = nums[i]; } return numsSize - remove; } |
沒有留言:
張貼留言