剑指offer - 数组

二维数组中的查找

问题描述:

在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

function Find(target, array) {
  // write code here
  for (let i = array.length - 1; i >= 0; i--) {
    if (array[i][0] <= target) {
      if (array[i].includes(target)) {
        return true;
      }
    }
  }
  return false;
}

数组中重复的数字

问题描述:

在一个长度为 n 的数组里的所有数字都在 0 到 n-1 的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为 7 的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字 2。

function duplicate(numbers, duplication) {
  // write code here
  //这里要特别注意~找到任意重复的一个值并赋值到duplication[0]
  //函数返回True/False
  if (!numbers || numbers.length == 0) {
    return false;
  }
  for (let i = 0; i < numbers.length; i++) {
    var num = numbers[i];
    if (numbers.indexOf(num) !== numbers.lastIndexOf(num)) {
      duplication[0] = num;
      return true;
    }
  }
  return false;
}

构建乘积数组

问题描述:

给定一个数组 A[0,1,...,n-1],请构建一个数组 B[0,1,...,n-1],其中 B 中的元素 B[i]=A[0]*A[1]*...*A[i-1]*A[i+1]*...*A[n-1]。不能使用除法。(注意:规定 B[0] = A[1] * A[2] * ... * A[n-1],B[n-1] = A[0] * A[1] * ... * A[n-2];)

function multiply(array) {
  // write code here
  const length = array.length;
  const newArray = [];
  for (let i = 0; i < length; i++) {
    newArray[i] = __multiply(array, i);
  }
  return newArray;
}

function __multiply(arr, index) {
  //返回数组arr中除了索引为index的数的乘积和
  const len = arr.length;
  var res = 1;
  for (let i = 0; i < len; i++) {
    if (i !== index) {
      res *= arr[i];
    } else {
      continue;
    }
  }
  return res;
}

猜你喜欢

转载自www.cnblogs.com/muzidaitou/p/12699929.html
今日推荐