阅读 55

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;
    }
}

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

文章分类
代码人生
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐