47
47
48
48
<!-- 这里可写通用的实现逻辑 -->
49
49
50
+ ** 方法一:排序**
51
+
52
+ 对 nums 进行排序。然后 l, r 分别指向 nums 首尾元素,判断两整数之和 s 与 k 的大小关系。
53
+
54
+ - 若 ` s == k ` ,说明找到了两个整数,满足和为 k,答案 ans 加 1,然后 l, r 向中间移动;
55
+ - 若 ` s > k ` ,则 r 指针向左移动;
56
+ - 若 ` s > k ` ,则 l 指针向右移动;
57
+ - 继续循环判断,直至 l >= r。
58
+
59
+ 循环结束,返回 ans。
60
+
61
+ 时间复杂度 O(nlogn),其中 n 为 nums 的长度。
62
+
50
63
<!-- tabs:start -->
51
64
52
65
### ** Python3**
57
70
class Solution :
58
71
def maxOperations (self , nums : List[int ], k : int ) -> int :
59
72
nums.sort()
60
- ans, l, r = 0 , 0 , len (nums) - 1
73
+ l, r, ans = 0 , len (nums) - 1 , 0
61
74
while l < r:
62
- if nums[l] + nums[r] > k:
75
+ s = nums[l] + nums[r]
76
+ if s == k:
77
+ ans += 1
78
+ l, r = l + 1 , r - 1
79
+ elif s > k:
63
80
r -= 1
64
- elif nums[l] + nums[r] < k:
65
- l += 1
66
81
else :
67
- ans += 1
68
82
l += 1
69
- r -= 1
70
83
return ans
71
84
```
72
85
@@ -81,14 +94,15 @@ class Solution {
81
94
int l = 0 , r = nums. length - 1 ;
82
95
int ans = 0 ;
83
96
while (l < r) {
84
- if (nums[l] + nums[r] > k) {
85
- r-- ;
86
- } else if (nums[l] + nums[r] < k) {
87
- l++ ;
97
+ int s = nums[l] + nums[r];
98
+ if (s == k) {
99
+ ++ ans;
100
+ ++ l;
101
+ -- r;
102
+ } else if (s > k) {
103
+ -- r;
88
104
} else {
89
- ans++ ;
90
- l++ ;
91
- r-- ;
105
+ ++ l;
92
106
}
93
107
}
94
108
return ans;
@@ -100,25 +114,53 @@ class Solution {
100
114
101
115
``` cpp
102
116
class Solution {
103
- public:
104
- int maxOperations(vector<int >& nums, int k) {
105
- int n = nums.size();
106
- sort(nums.begin(), nums.end());
107
- int cnt = 0;
108
- int i = 0, j = n - 1;
109
- while (i < j) {
110
- if (nums[ i] + nums[ j] == k) {
111
- i++;
112
- j--;
113
- cnt++;
114
- } else if (nums[ i] + nums[ j] > k) {
115
- j--;
116
- } else
117
- i++;
117
+ public:
118
+ int maxOperations(vector<int >& nums, int k) {
119
+ sort(nums.begin(), nums.end());
120
+ int cnt = 0;
121
+ int i = 0, j = nums.size() - 1;
122
+ while (i < j) {
123
+ if (nums[ i] + nums[ j] == k) {
124
+ i++;
125
+ j--;
126
+ cnt++;
127
+ } else if (nums[ i] + nums[ j] > k) {
128
+ j--;
129
+ } else {
130
+ i++;
131
+ }
132
+ }
133
+ return cnt;
118
134
}
119
- return cnt;
120
- }
121
135
};
122
136
```
123
137
138
+ ### **Go**
139
+
140
+ ```go
141
+ func maxOperations(nums []int, k int) int {
142
+ sort.Ints(nums)
143
+ l, r, ans := 0, len(nums)-1, 0
144
+ for l < r {
145
+ s := nums[l] + nums[r]
146
+ if s == k {
147
+ ans++
148
+ l++
149
+ r--
150
+ } else if s > k {
151
+ r--
152
+ } else {
153
+ l++
154
+ }
155
+ }
156
+ return ans
157
+ }
158
+ ```
159
+
160
+ ### ** ...**
161
+
162
+ ```
163
+
164
+ ```
165
+
124
166
<!-- tabs: end -->
0 commit comments