首页 > 其他 > 详细

LeetCode-704. Binary Search

时间:2021-09-21 01:00:59      阅读:9      评论:0      收藏:0      [点我收藏+]

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. Binary Search

原文:https://www.cnblogs.com/pengcode/p/15311824.html

(0)
(0)
   
举报
评论 一句话评论(0
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!