js 面试算法题(后续更新)

2023-12-25 17:33:10

1.现给定?个整数数组(数组长度大于等于 5)nums 和?个整数目标值 target,请你在该数组中找出和为目标值 target 的那 n(n<nums.length) 个整数,并返回它们的数组(如果有多个下标组合都满足,则返回下标和最小的那一组)的下标。 注意:数组中同?个元素在答案?不能重复出现。 比如输入:nums = [3,2,4,5,7],n=3,target = 10 输出:[0,1,3]

function findIndexes(nums, n, target) {
  let result = [];
  let current = [];
  backtrack(nums, result, current, n, 0, 0, target);
  return result[0];
}

function backtrack(nums, result, current, n, start, sum, target) {
  if (current.length === n && sum === target) {
    if (result.length === 0) {
      result.push(current.slice());
    } else if (compareIndexes(current, result[0]) < 0) {
      result[0] = current.slice();
    }
    return;
  }
  for (let i = start; i < nums.length; i++) {
    if (current.includes(i)) continue; // 避免重复使用同一个元素
    current.push(i);
    backtrack(nums, result, current, n, i + 1, sum + nums[i], target);
    current.pop();
  }
}

function compareIndexes(indexes1, indexes2) {
  for (let i = 0; i < indexes1.length; i++) {
    if (indexes1[i] < indexes2[i]) {
      return -1;
    } else if (indexes1[i] > indexes2[i]) {
      return 1;
    }
  }
  return 0;
}

let nums = [3, 2, 4, 5, 7];
let n = 3;
let target = 10;
let result = findIndexes(nums, n, target);
console.log(result);

文章来源:https://blog.csdn.net/lin85253788/article/details/135202456
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。