Interview 150
Remove Element
- Problem
- LC 27
- File
- interview150_LC27RemoveElement.java
- Path
- pkg5leetcode/interview150/interview150_LC27RemoveElement.java
- Package
- pkg5leetcode.interview150
- Command
- java pkg5leetcode/interview150/interview150_LC27RemoveElement.java
- Approach
- Two pointers skip values equal to val.
- Complexity
- Time O(n), Space O(1)
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg5leetcode.interview150;2 3/*4 * Remove Element | LC 275 * APPROACH: Two pointers skip values equal to val.6 * COMPLEXITY: Time O(n), Space O(1)7 */8public class interview150_LC27RemoveElement {9 static int removeElement(int[] nums, int val) {10 int k = 0;11 for (int x : nums) if (x != val) nums[k++] = x;12 return k;13 }14 15 public static void main(String[] args) {16 int[] a = {3, 2, 2, 3};17 check(removeElement(a, 3) == 2, "case1");18 int[] b = {0, 1, 2, 2, 3, 0, 4, 2};19 check(removeElement(b, 2) == 5, "case2");20 System.out.println("all tests passed");21 }22 23 static void check(boolean cond, String name) {24 if (!cond) throw new AssertionError("FAILED: " + name);25 System.out.println(" PASS " + name);26 }27}