附上我的github倉庫,會(huì)不斷更新leetcode解題答案,提供一個(gè)思路,大家共勉
希望可以給star脑题,鼓勵(lì)繼續(xù)更新解題思路
author: thomas
No561:Array Partition I(
Easy
)
題目
Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible.
- Example 1:
Input: [1,4,3,2]
Output: 4
Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min(3, 4).
- Note:
n is a positive integer, which is in the range of [1, 10000].
All the integers in the array will be in the range of [-10000, 10000].
意思是:給一個(gè)2n長度的數(shù)組,兩兩為一組铜靶,然后取每組的最小值叔遂,最后對(duì)所有組的min值求和,問如何匹配保證這個(gè)求和的值最大
思路
就是給2n個(gè)數(shù)分組争剿,兩兩一組已艰,使用所有組中小的那個(gè)數(shù)加起來和最小。
既然我們兩兩分組蚕苇,并且只取最小的那個(gè)值哩掺,那兩個(gè)值中較大的值就浪費(fèi)了。為了使浪費(fèi)最低涩笤,那就每個(gè)分組都保證大的那個(gè)值只比小的那個(gè)值大一點(diǎn)點(diǎn)(也就是最接近小的那個(gè)值)疮丛。
先將所有數(shù)排序,然后就是以排序后的值從前往后每2個(gè)值為一組(這樣就保證每個(gè)組中大的值最接近小的值)辆它,由于每個(gè)分組都是最小的值,所以我們?nèi)〉闹稻褪俏恢?履恩,3锰茉,5...的值
代碼
//
let arr = [1,4,3,2];
var arrayPariSum = function(arr) {
let first = 1,
end = arr.length;
arr = QuickSort(arr, first, end); // 這是調(diào)用快排函數(shù)
let len = arr.length,
sum = 0;
for (let i = 0; i < len; i += 2) { //只取1,3切心,5..位置的值相加
sum += arr[i];
}
return sum;
};
console.log(arrayPariSum(arr));
No566:Reshape the Matrix(
Easy
)
題目
題目:給一個(gè)二維數(shù)組和兩個(gè)數(shù)字飒筑,返回一個(gè)二維數(shù)組片吊,第一個(gè)數(shù)字代表返回的數(shù)組的行,第二個(gè)數(shù)字代表列协屡。
Example 1:
Input:
nums =
[[1,2],
[3,4]]
r = 1, c = 4
Output:
[[1,2,3,4]]
Explanation:
The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the previous list.
Example 2:
Input:
nums =
[[1,2],
[3,4]]
r = 2, c = 4
Output:
[[1,2],
[3,4]]
Explanation:
There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original matrix.
思路
- 剛開始想邏輯想不明白俏脊,可能是想循環(huán)一下搞定,但是不行肤晓,只能在循環(huán)外面創(chuàng)建兩個(gè)變量來控制要返回的數(shù)組的接收:
- javascript在多維數(shù)組的創(chuàng)建上和其他語言不同爷贫,沒有多維數(shù)組,所以只能自己不斷地在內(nèi)部創(chuàng)建新的數(shù)組(用到的時(shí)候补憾,再創(chuàng)建)
代碼
<script>
let arr = [[1,2],[3,4],[5,6]];
let r = 2, c = 3;
let matrixReshape = function(arr, r, c) {
if (arr === null) {
return false;
}
if (arr.length * arr[0].length !== r * c) {
return arr;
}
let [tempr, tempc,row, col] = [0, 0, arr.length, arr[0].length],
res = [];
res[tempr] = [];// 這里要先在數(shù)組res中創(chuàng)建一個(gè)新的數(shù)組
for (let i = 0; i < row; i++) {
for (let j = 0; j < col; j++) {
res[tempr][tempc] = arr[i][j];
if (tempc === c-1) { // 第一行滿了
tempr += 1;
if (tempr < r) {
res[tempr] = [];// 如果滿足條件漫萄,在內(nèi)部多創(chuàng)建一個(gè)空數(shù)組
}
tempc = 0;
continue;
}
tempc += 1;
}
}
return res;
}
console.log(matrixReshape(arr, r, c))