-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRemoveElement.cs
73 lines (59 loc) · 1.82 KB
/
RemoveElement.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LeetCodeSolutions
{
// Source: https://leetcode.com/problems/remove-element
// Author: Jalal Shabo
// Date : 11/24/2023
// Time Complexity: O(n) one look through array with two pointers and one look through the array to count unique numbers.
// Space Complexity: O(n)
// two pointer solution is faster, but the simplicity and readability of solution two has its own benefits
public static class RemoveElement
{
public static int RemoveElementSolution(int[] nums, int val)
{
int leftPtr = 0, rightPtr = nums.Length - 1;
while (leftPtr < rightPtr)
{
if (nums[leftPtr] == val && nums[rightPtr] != val)
{
(nums[leftPtr], nums[rightPtr]) = (nums[rightPtr], nums[leftPtr]);
leftPtr++;
rightPtr--;
}
if (nums[leftPtr] != val)
{
leftPtr++;
}
if (nums[rightPtr] == val)
{
rightPtr--;
}
}
int count = 0;
foreach (int i in nums)
{
if (i == val)
{
break;
}
count++;
}
return count;
}
public static int RemoveElementSolutionTwo(int[] nums, int val)
{
int uniqueIntCount = 0;
foreach (int num in nums)
{
if (num != val) {
nums[uniqueIntCount] = num;
uniqueIntCount++;
}
}
return uniqueIntCount;
}
}
}