力扣算法——在排序数组中查找元素的第一个和最后一个位置

88 阅读2分钟

1、TypeScript 实现的二分查找和查找最大/最小元素的代码示例:

function binarySearch(arr: number[], target: number): number {  
  let left = 0;  
  let right = arr.length - 1;  
  while (left <= right) {  
    let mid = left + (right - left) / 2;  
    if (arr[mid] === target) {  
      return mid;  
    } else if (arr[mid] < target) {  
      left = mid + 1;  
    } else {  
      right = mid - 1;  
    }  
  }  
  return -1;  
}  
  
function findFirstAndLastIndex(arr: number[]): number {  
  let left = 0;  
  let right = arr.length - 1;  
  let minIndex = null;  
  let maxIndex = null;  
  
  while (left <= right) {  
    let mid = left + (right - left) / 2;  
    if (arr[mid] < arr[minIndex]) {  
      minIndex = mid;  
    } else if (arr[mid] > arr[maxIndex]) {  
      maxIndex = mid;  
    } else if (arr[mid] === arr[minIndex] && target < arr[mid]) {  
      left = mid + 1;  
    } else {  
      right = mid - 1;  
    }  
  }  
  
  return maxIndex;  
}

binarySearch 函数接受一个整数数组和一个目标值作为参数,返回目标值在数组中的索引。如果目标值不存在于数组中,则返回 -1

findFirstAndLastIndex 函数接受一个整数数组作为参数,返回目标值在数组中的第一个和最后一个索引。如果目标值不存在于数组中,则返回 null

这两个函数都使用了二分查找算法来查找目标值在数组中的索引。binarySearch 函数在每次迭代中将数组的一半与目标值进行比较,如果它们相等,则返回当前索引。如果目标值比数组的一半小,则在左半部分继续查找。如果目标值比数组的一半大,则在右半部分继续查找。findFirstAndLastIndex 函数则需要在每次迭代中将数组的一半与目标值进行比较,如果它们相等并且当前元素是目标值,则返回当前索引。如果当前元素是目标值,则在左半部分继续查找。如果当前元素不是目标值,则在右半部分继续查找。

2、JavaScript的Array.indexOf和Array.lastIndexOf方法来实现线性搜索算法,并结合循环和条件判断来实现查找第一个和最后一个元素的位置

function linearSearch(arr, target) {  
  var firstIndex = 0;  
  var lastIndex = arr.length - 1;  
  
  while (firstIndex <= lastIndex) {  
    var currentIndex = firstIndex + (lastIndex - firstIndex) / 2;  
  
    if (arr[currentIndex] === target) {  
      return currentIndex;  
    } else if (arr[currentIndex] < target) {  
      firstIndex = currentIndex + 1;  
    } else {  
      lastIndex = currentIndex - 1;  
    }  
  }  
  
  return -1;  
}  
  
function findFirstAndLastIndex(arr) {  
  var left = 0;  
  var right = arr.length - 1;  
  var result = -1;  
  
  while (left <= right) {  
    var mid = left + (right - left) / 2;  
  
    if (arr[mid] < arr[result]) {  
      left = mid + 1;  
    } else {  
      right = mid - 1;  
    }  
  }  
  
  return result;  
}  
  
// 示例用法  
var arr = [3, 5, 2, 1, 6];  
var target = 5;  
var firstIndex = linearSearch(arr, target);  
if (firstIndex !== -1) {  
  console.log(`The first element of the array is at index ${firstIndex}`);  
} else {  
  console.log(`The first element of the array is not found`);  
}  
  
var lastIndex = findFirstAndLastIndex(arr);  
if (lastIndex !== -1) {  
  console.log(`The last element of the array is at index ${lastIndex}`);  
}

如果目标值不存在于数组中,则返回 -1
findFirstAndLastIndex函数接受一个排序数组作为参数,返回目标值在数组中的第一个和最后一个索引。如果目标值不存在于数组中,则返回 null
在示例用法中,我们使用linearSearch函数来查找排序数组中的第一个和最后一个元素,并使用findFirstAndLastIndex函数来查找第一个和最后一个元素的位置。