检查数组并实现bool方法

千层蛋糕

您有一个数组。如果数组中任意两个数字加到零,则返回true不管有多少对,只要有一对加到零,就返回return true如果为零,则仅true当存在多个时才返回

我编写了两个函数,一个用于检查每个函数,最后一个用于组合两个函数,false如果没有满足则返回

def checkZero(array)
  zerocount = 0
  for j in 0..array.count
    if array[j] == 0
      zerocount += 1
    end
  end
  if zerocount > 1 #this part seems to not be working, not sure why
    return true
  else
    return false
  end
end

def checkNegative(array)
  for j in 0..array.count
    neg = -array[j] #set a negative value of the current value
    if array.include?(neg) #check to see whether the negative exists in the array
      return true
    else
      return false
    end
  end
end

def checkArray(array)
  if checkZero(array) == true or checkNegative(array) == true
    return true
  else
    return false
  end
end

然后运行类似

array = [1,2,3,4,0,1,-1]
checkArray(array)

到目前为止,Ruby没有返回任何东西。我只是一片空白。我感觉自己return不对。

肖阿里

问题可能是您没有输出结果。

array = [1,2,3,4,0,1,-1]
puts checkArray(array)

checkArray如果对性能(O(n ^ 2))的关注不是很大,则可以按如下所示编写方法

def check_array(array)
  array.combination(2).any?{|p| p.reduce(:+) == 0}
end

效率更高的(O(n log n))解决方案是:

def check_array(array)
  array.sort! # `array = array.sort` if you need the original array unchanged
  i, j = 0, array.size - 1
  while i < j
    sum = array[i] + array[j]
    if sum > 0
      j -= 1
    elsif sum < 0
      i += 1
    else
      return true
    end
  end
  return false
end

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章