LeetCode-704. Binary Search

发布时间:2022-07-05 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了LeetCode-704. Binary Search脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

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. Binary Search全部内容,希望文章能够帮你解决LeetCode-704. Binary Search所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。