LeetCode-704. Binary Search

Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.

You must write an algorithm with O(log n) runtime complexity.

Example 1:

Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in nums and its index is 4

Example 2:

Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: 2 does not exist in nums so return -1

Constraints:

  • 1 <= nums.length <= 10^4
  • -10^4 < nums[i], target < 10^4
  • All the integers in nums are unique.
  • nums is sorted in ascending order.
class Solution {
  //nums用到的数组。   target所选择的索引目标
    public int search(int[] nums, int target) {
      //对nums数组进行遍历
        for(int i =0;i < nums.length;i++){
          //如果nums遍历之中的索引i的值 正好等于 target
            if(nums[i] == target){
              //那么返回i
                return i;
            }
            
        }
      //否则返回-1
        return -1;
    }
}
上一篇:LeetCode刷题日记 704.二分查找


下一篇:数据库中的数据是如何被***拖取的?