其他分享
首页 > 其他分享> > leetcode之求两数之和—有序数组

leetcode之求两数之和—有序数组

作者:互联网

二分法

traget-当前值=我们二分要找的值,
那就二分去找,
去left,right的区间范围去找
直到 left和right重叠还找不到,说明真找不到了

let arr = [1, 2, 3, 4, 5, 6];
function sum(arr, target) {
  for (let i = 0; i < arr.length; i++) {
    let tem = target - arr[i];
    let left = i + 1, right = arr.length - 1;
    while (left <= right) {
    // left和right重叠还找不到,说明真找不到了
      let mid = parseInt((left + right) / 2);
      if (arr[mid] === tem) {
        return [i, mid];
      } else
        if (arr[mid] > tem) {
          right = mid - 1;
        } else {
          left = mid + 1;
        }
    }
  }
  return -1;
}
console.log(sum(arr, 5));
时间复杂度为 O(n*logn)

双指针算法

思路:
如果左+右小于目标值,右边不动左边++
如果左+右大于目标值,左边不动右边++
直到指针重叠还找不到就结束
过程中找到了也结束

let arr = [1, 2, 3, 4, 5, 6];
function sum(arr, target) {
  //双指针算法
  let left = 0, right = arr.length - 1;
  while (left <= right) {
    let all = arr[left] + arr[right];
    if (all == target) {
      return [left, right]
    } else if (all < target) {
      left++;
    } else {
      right--;
    }
  }
  return -1;
}
console.log(sum(arr, 111))

标签:之求,arr,right,target,mid,let,leetcode,两数,left
来源: https://blog.csdn.net/qq_36262295/article/details/116399313