From 7e297a3605f1546eb7242300e4f9e6047af2925c Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Thu, 2 Jan 2025 15:05:33 +0100 Subject: [PATCH] =?UTF-8?q?java:=20add=20=C2=AB27.=20Remove=20Element?= =?UTF-8?q?=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit URL: https://leetcode.com/problems/remove-element/ --- java/remove-element.java | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 java/remove-element.java diff --git a/java/remove-element.java b/java/remove-element.java new file mode 100644 index 0000000..61f48bd --- /dev/null +++ b/java/remove-element.java @@ -0,0 +1,32 @@ +class Solution { + private static int skipVal(int[] nums, int val, int i) { + for ( + /* no-op */ ; i >= 0 && nums[i] == val; /* no-op */ ) { + --i; + } + + return i; + } + + public int removeElement(int[] nums, int val) { + var r = skipVal(nums, val, nums.length - 1); + + int l; + for (l = 0; l < r; ++l) { + if (nums[l] == val) { + var tmp = nums[l]; + nums[l] = nums[r]; + nums[r] = tmp; + + r = skipVal(nums, val, r); + } + } + + // shift ‹l› to the first ‹val› + while (l < nums.length && nums[l] != val) { + ++l; + } + + return l; + } +}