54
54
55
55
<!-- 这里可写通用的实现逻辑 -->
56
56
57
- 排序 + 贪心。
57
+ ** 方法一:贪心**
58
+
59
+ 要使得数组中最大数对和的值最小,那么我们可以将数组中最小的数和最大的数配对,次小的数和次大的数配对,依此类推。
60
+
61
+ 因此,我们可以先对数组进行排序,然后使用两个指针分别指向数组的两端,求出两个指针指向的数的和,更新最大数对和的值,然后将左指针右移一位,右指针左移一位,继续进行操作,直到两个指针相遇为止,即可得到最小的最大数对和。
62
+
63
+ 时间复杂度 $O(n \times \log n)$,空间复杂度 $O(\log n)$。其中 $n$ 是数组的长度。
58
64
59
65
<!-- tabs:start -->
60
66
66
72
class Solution :
67
73
def minPairSum (self , nums : List[int ]) -> int :
68
74
nums.sort()
69
- res, n = 0 , len (nums)
70
- for i in range (n >> 1 ):
71
- res = max (res, nums[i] + nums[n - i - 1 ])
72
- return res
75
+ n = len (nums)
76
+ return max (x + nums[n - i - 1 ] for i, x in enumerate (nums[: n >> 1 ]))
73
77
```
74
78
75
79
### ** Java**
@@ -80,11 +84,11 @@ class Solution:
80
84
class Solution {
81
85
public int minPairSum (int [] nums ) {
82
86
Arrays . sort(nums);
83
- int res = 0 , n = nums. length;
84
- for (int i = 0 ; i < ( n >> 1 ) ; ++ i) {
85
- res = Math . max(res , nums[i] + nums[n - i - 1 ]);
87
+ int ans = 0 , n = nums. length;
88
+ for (int i = 0 ; i < n >> 1 ; ++ i) {
89
+ ans = Math . max(ans , nums[i] + nums[n - i - 1 ]);
86
90
}
87
- return res ;
91
+ return ans ;
88
92
}
89
93
}
90
94
```
@@ -96,25 +100,25 @@ class Solution {
96
100
public:
97
101
int minPairSum(vector<int >& nums) {
98
102
sort(nums.begin(), nums.end());
99
- int res = 0, n = nums.size();
100
- for (int i = 0; i < ( n >> 1) ; ++i) {
101
- res = max(res , nums[ i] + nums[ n - i - 1] );
103
+ int ans = 0, n = nums.size();
104
+ for (int i = 0; i < n >> 1; ++i) {
105
+ ans = max(ans , nums[ i] + nums[ n - i - 1] );
102
106
}
103
- return res ;
107
+ return ans ;
104
108
}
105
109
};
106
110
```
107
111
108
112
### **Go**
109
113
110
114
```go
111
- func minPairSum(nums []int) int {
115
+ func minPairSum(nums []int) (ans int) {
112
116
sort.Ints(nums)
113
- res, n := 0, len(nums)
114
- for i := 0; i < (n >> 1); i++ {
115
- res = max(res, nums[i] +nums[n-i-1 ])
117
+ n := len(nums)
118
+ for i, x := range nums[:n>>1] {
119
+ ans = max(ans, x +nums[n-1-i ])
116
120
}
117
- return res
121
+ return
118
122
}
119
123
120
124
func max(a, b int) int {
@@ -125,6 +129,20 @@ func max(a, b int) int {
125
129
}
126
130
```
127
131
132
+ ### ** TypeScript**
133
+
134
+ ``` ts
135
+ function minPairSum(nums : number []): number {
136
+ nums .sort ((a , b ) => a - b );
137
+ let ans = 0 ;
138
+ const n = nums .length ;
139
+ for (let i = 0 ; i < n >> 1 ; ++ i ) {
140
+ ans = Math .max (ans , nums [i ] + nums [n - 1 - i ]);
141
+ }
142
+ return ans ;
143
+ }
144
+ ```
145
+
128
146
### ** ...**
129
147
130
148
```
0 commit comments