-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathEasy_27_RemoveElement.kt
More file actions
59 lines (49 loc) · 1.18 KB
/
Easy_27_RemoveElement.kt
File metadata and controls
59 lines (49 loc) · 1.18 KB
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
package com.boycoder.problems.array
/**
* @Author: zhutao
* @datetime: 2021/6/4
* @desc:
*/
object Easy_27_RemoveElement {
/**
* Two pointer start from two side of array
*/
fun remove(array: IntArray, target: Int): Int {
var left = 0
var right = array.size - 1
while (left <= right) {
if (array[right] == target) {
right--
continue
}
if (array[left] == target) {
array[left] = array[right]
right--
left++
} else {
left++
}
}
return right + 1
}
/**
* Two point: slow and fast, start from beginning
*/
fun remove1(array: IntArray, target: Int): Int {
var slow: Int = 0
var fast: Int = 0
val size = array.size
while (fast < size && slow <= fast) {
if (array[fast] == target) {
fast++
} else {
if (slow != fast) {
array[slow] = array[fast]
}
fast++
slow++
}
}
return slow
}
}