LeetCode——954.二倍数对数组

给定一个长度为偶数的整数数组 A,只有对 A 进行重组后可以满足 “对于每个 0 <= i < len(A) / 2,都有 A[2 * i + 1] = 2 * A[2 * i]” 时,返回 true;否则,返回 false。
示例 1:

输入:[3,1,3,6]
输出:false

示例 2:

输入:[2,1,2,6]
输出:false

示例 3:

输入:[4,-2,2,-4]
输出:true
解释:我们可以用 [-2,-4] 和 [2,4] 这两组组成 [-2,-4,2,4] 或是 [2,4,-2,-4]

示例 4:

输入:[1,2,4,16,8,4]
输出:false

提示:

0 <= A.length <= 30000
A.length 为偶数
-100000 <= A[i] <= 100000

思路

A中包含正数、负数、和0,先将这三者分离开,保存正数数组、负数数组、0的个数。
如果出现0的个数/正数的个数/负数的个数不为偶数,就返回false。

将正数数组从小到大排序,负数数组从大到小排序。

当正数数组还有元素时循环:
如果第一个元素的两倍存在于数组中,那么将数组中去掉第一个元素和第一个元素的两倍;如果不存在就返回false。

负数数组做同样处理。
如果正数、负数数组处理完,还没返回false,说明两个数组都可以满足条件。就返回true。

总代码:

/**
 * @param {number[]} A
 * @return {boolean}
 */
var canReorderDoubled = function(A) {
  let negative = []
  let positive = []
  let zeroNum = 0
  A.forEach(el => { // 将正数、负数和0分开
    if (el === 0) {
      zeroNum ++
    } else if (el < 0) {
      negative.push(el)
    } else {
      positive.push(el)
    }
  })
  
  if (zeroNum % 2 !== 0 || negative.length % 2 !== 0 || positive.length % 2 !== 0) {
    return false
  }
  
  negative.sort((a,b) => b - a)
  positive.sort((a,b) => a - b)
  
  
  while (negative.length) {
    if (negative.includes(negative[0] * 2)) {
      let index = negative.indexOf(negative[0] * 2)
      negative = negative.slice(1, index).concat(negative.slice(index+1))
    } else {
      return false
    }
  }
  while (positive.length) {
    if (positive.includes(positive[0] * 2)) {
      let index = positive.indexOf(positive[0] * 2)
      positive = positive.slice(1, index).concat(positive.slice(index+1))
    } else {
      return false
    }
  }
  return true;
};

猜你喜欢

转载自blog.csdn.net/romeo12334/article/details/84957408