В предоставленном упорядоченном по возрастанию целочисленном слайсе, оставить уникальные элементы полюс один возможный дубликат. Вернуть количество таких элементов.
| Go | 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
| // [url]https://leetcode.com/studyplan/top-interview-150/[/url]
package topInterview
// removeDuplicates
//
// 80. Remove Duplicates from Sorted Array II
// Given an integer array nums sorted in non-decreasing order, remove some duplicates in-place such that each unique element appears at most twice. The relative order of the elements should be kept the same.
//
// Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.
//
// Return k after placing the final result in the first k slots of nums.
//
// Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.
//
// Custom Judge:
//
// The judge will test your solution with the following code:
//
// int[] nums = [...]; // Input array
// int[] expectedNums = [...]; // The expected answer with correct length
//
// int k = removeDuplicates(nums); // Calls your implementation
//
// assert k == expectedNums.length;
//
// for (int i = 0; i < k; i++) {
// assert nums[i] == expectedNums[i];
// }
//
// If all assertions pass, then your solution will be accepted.
//
// Example 1:
//
// Input: nums = [1,1,1,2,2,3]
// Output: 5, nums = [1,1,2,2,3,_]
// Explanation: Your function should return k = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively.
// It does not matter what you leave beyond the returned k (hence they are underscores).
// Example 2:
//
// Input: nums = [0,0,1,1,1,1,2,3,3]
// Output: 7, nums = [0,0,1,1,2,3,3,_,_]
// Explanation: Your function should return k = 7, with the first seven elements of nums being 0, 0, 1, 1, 2, 3 and 3 respectively.
// It does not matter what you leave beyond the returned k (hence they are underscores).
//
// Constraints:
//
// 1 <= nums.length <= 3 * 104
// -104 <= nums[i] <= 104
// nums is sorted in non-decreasing order.//
func removeDuplicatesII(nums []int) int {
// Инициировать переменные
indexMutable := 0 // Индекс изменяемого элемента
indexChecked := 1 // Индекс проверяемого элемента
idDubFound := false // Флаг, который указывает на то был ли уже найден дубликат
lengthNums := len(nums) // Длина слайса nums
// Если в слайсе nums меньше двух элементов
if lengthNums < 2 {
// Возвращаем длину слайса nums
return lengthNums
}
// Прервать цикл если индекс проверяемого элемента достиг длинны слайса
for indexChecked < lengthNums {
// Если изменяемый элемент и проверяемый элемент равны и дубликат ранее не найден
if nums[indexMutable] == nums[indexChecked] && idDubFound {
// Увеличить индекс проверяемого элемента на один
indexChecked++
// Прервать текущую итерацию цикла
continue
}
// Если изменяемый элемент и проверяемый элемент равны и дубликат ранее найден
if nums[indexMutable] == nums[indexChecked] && !idDubFound {
// Увеличить индекс изменяемого элемента на один
indexMutable++
// Изменить значение изменяемого элемента на значение проверяемого элемента
nums[indexMutable] = nums[indexChecked]
// Увеличить индекс проверяемого элемента на один
indexChecked++
// Установить признак того что дубликат найден
idDubFound = true
// Прервать текущую итерацию цикла
continue
}
// Если проверяемый элемент больше изменяемого
if nums[indexChecked] > nums[indexMutable] {
// Увеличить индекс изменяемого элемента на один
indexMutable++
// Изменить значение изменяемого элемента на значение проверяемого элемента
nums[indexMutable] = nums[indexChecked]
// Увеличить индекс проверяемого элемента на один
indexChecked++
// Сбросить признак того что дубликат найден
idDubFound = false
}
}
// Вернуть индекс изменяемого элемента + 1
return indexMutable + 1
} |
|
| Go | 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
| func TestRemoveDuplicatesII(t *testing.T) {
data := []struct {
nums []int
expected int
numsAfter []int
}{
{
nums: []int{},
expected: 0,
numsAfter: []int{},
},
{
nums: []int{1},
expected: 1,
numsAfter: []int{1},
},
{
nums: []int{-9, -9, -2, -2, -2, 0, 0, 0, 1},
expected: 7,
numsAfter: []int{-9, -9, -2, -2, 0, 0, 1},
},
{
nums: []int{1, 1, 1, 2, 2, 3},
expected: 5,
numsAfter: []int{1, 1, 2, 2, 3},
},
{
nums: []int{0, 0, 1, 1, 1, 1, 2, 3, 3},
expected: 7,
numsAfter: []int{0, 0, 1, 1, 2, 3, 3},
},
}
for i, datum := range data {
result := removeDuplicatesII(datum.nums)
if result != datum.expected || !reflect.DeepEqual(datum.nums[:datum.expected], datum.numsAfter) {
t.Errorf("unexpected result for test index %d expected [%+v, %+v] got [%+v, %+v]", i, datum.expected, datum.numsAfter, result, datum.nums[:datum.expected])
}
}
} |
|
| Code | 1
2
3
| === RUN TestRemoveDuplicatesII
--- PASS: TestRemoveDuplicatesII (0.00s)
PASS |
|
| https://github.com/alhaos/problems
|