- Sponsor
-
Notifications
You must be signed in to change notification settings - Fork 244
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
有一堆整数,请把他们分成三份,确保每一份和尽量相等(11,42,23,4,5,6 4 5 6 11 23 42 56 78 90) #133
Comments
var a = [11, 42, 23, 4, 5, 6, 4, 5, 6, 11, 23, 42, 56, 78, 90]
function oneToThreeArr(arr){
let res = [{sum: 0, arr: []}, {sum: 0, arr: []}, {sum: 0, arr: []}]
//从大到小排序,每次把最大的值给到和最小的数组中
arr = arr.slice().sort((a,b) => b - a);//拷贝一份再排序
arr.map(item => {
let min = res.sort((a,b) => a.sum - b.sum)[0];//拿到当前和最小的那个数组
min.sum += item;
min.arr.push(item);
})
return res;
}
console.log(oneToThreeArr(a)); |
let a = [11, 42, 23, 4, 5, 6, 4, 5, 6, 11, 23, 42, 56, 78, 90];
function dengfenthere(arr) {
let result = Array.from({ length: 3 }, () => ({ sum: 0, arr: [] }));
let arr2 = arr.sort((a, b) => b - a);
for (let key of arr2) {
let index = 0;
if (result[1].sum < result[index].sum) {
index = 1;
}
if (result[2].sum < result[index].sum) {
index = 2;
}
result[index].sum += key;
result[index].arr.push(key);
}
return result;
}
dengfenthere(a); |
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No description provided.
The text was updated successfully, but these errors were encountered: