zoukankan      html  css  js  c++  java
  • 7kyu (难度系数kyu阶段数值越大难度越低) 数组分组及求和


    几个人排成一排,分成两队。
    第一个人进入一队,第二个人进入第二队,第三个人进入第一队,以此类推。


    给定一个正整数的数组(人的权重),返回两个整数的新数组/元组,
    其中第一个是第1组的总重量,第二个是第2组的总重量。
    数组大小至少为1.所有数字都是正数。

    function rowWeights(array){
    //your code here
    let a = 0;
    let b = 0;
    for (let i=0;i<array.length;i++) {
    if (i % 2 == 0) {
    a += array[i];
    } else {
    b += array[i];
    }
    }
    return new Array(a, b);

    }

    大神的解:

    function rowWeights(array){
    var arr = [0, 0];
    for (var i = 0; i < array.length; i++) {
    i % 2 == 0 ? arr[0] += array[i] : arr[1] += array[i];
    }
    return arr;
    }

    function rowWeights(array){
      let t1 = array.filter((x, i)=>i%2==0).reduce((a,item)=>a+item,0);
      let t2 = array.filter((x, i)=>i%2!=0).reduce((a,item)=>a+item,0);
      
      return [t1, t2]
    }
    rowWeights=arr=>arr.reduce((a,b,i)=>(a[i%2]+=b,a),[0,0])


    const rowWeights = arr => arr.reduce((a, w, i) => (a[i%2]+=w, a), [0, 0]);
    const rowWeights = a => a.reduce(([s1,s2],n,i)=> i%2 ? [s1,s2+n]: [s1+n, s2] , [0,0])
    function rowWeights(array) {
      return array.reduce((t, x, i) => {
        t[i % 2] += x;
        return t;
      }, [0, 0]);
    }
    function rowWeights(array) {
      return array.reduce((a, b, i) => (a[i%2] += b, a), [0, 0]);
    }
    function rowWeights(a,f=0,s=0){
      return (a.map((x,i)=>i%2?s+=x:f+=x),[f,s]);
    }




    本文仅提供参考,是本人闲时所写笔记,如有错误,还请赐教,作者:阿蒙不萌,大家可以随意转载

  • 相关阅读:
    React在componentDidMount里面发送请求
    React 术语词汇表
    React里受控与非受控组件
    React和Vue等框架什么时候操作DOM
    【LeetCode】79. Word Search
    【LeetCode】91. Decode Ways
    【LeetCode】80. Remove Duplicates from Sorted Array II (2 solutions)
    【LeetCode】1. Two Sum
    【LeetCode】141. Linked List Cycle (2 solutions)
    【LeetCode】120. Triangle (3 solutions)
  • 原文地址:https://www.cnblogs.com/huchong-bk/p/11208184.html
Copyright © 2011-2022 走看看