Closed congr closed 5 years ago
My first naive code(AC) - O(N)
class Solution {
public int removeElement(int[] nums, int val) {
int left = 0, right = nums.length-1;
while (left <= right) { // !!! [2] case
while (left < nums.length && nums[left] != val) left++;
while (right >= 0 && nums[right] == val) right--;
if (left >= right) return left; // !!
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
}
return left;
}
}
A lot shorter code
class Solution {
public int removeElement(int[] nums, int val) {
int k = 0;
for (int i = 0; i < nums.length; i++)
if (nums[i] != val) nums[k++] = nums[i];
return k;
}
}
https://leetcode.com/problems/remove-element/