leetcode第四题

题目描述:

找出两个数组中的中位数

解答:

 mounted() {
    let result = this.findCenterNum([1, 9], [4, 7])
    console.log(result);
  },
  methods: {
    findCenterNum(arr1, arr2) {
      let arr = arr1.concat(arr2)
      arr.sort(function(a,b){
        /*
        * return b-a; —> 降序排序
        * return a-b; —> 升序排列
        */
        return a-b;
      })
      console.log(arr);
      if(arr.length % 2 == 0) {
        return (arr[arr.length/2 - 1] + arr[arr.length/2]) / 2
      } else {
        return arr[Math.round(arr.length / 2)]
      }
    }
  }

 

posted @ 2021-05-18 17:37  栗子米  阅读(21)  评论(0编辑  收藏  举报