LeetCode刷题集——704.二分查找

题目描述

给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target ,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。

解题思路

  1. 首先定义low,high;
  2. 取中间的mid,如果nums[mid]=target,返回mid下标;
  3. 如果nums[mid]大于target,则high = mid - 1;
  4. 如果nums[mid]小于target,则low = mid + 1;
  5. 若不存在则返回-1;

C语言源代码

int search(int* nums, int numsSize, int target){
    int low = 0;
    int high = numsSize - 1;
        while(low <= high){
            int mid = (low + high) / 2;
            if(nums[mid] == target){
                return mid;
            }else if(nums[mid] < target){
                low = mid + 1;
            }else if(nums[mid] > target){
                high = mid - 1;
            }
        }
        return -1;
}

Java源代码

class Solution {
    public int search(int[] nums, int target) {
        int low = 0;
        int high = nums.length - 1;
        while(low <= high){
            int mid = (low + high) / 2;
            if(nums[mid] == target){
                return mid;
            }else if(nums[mid] < target){
                low = mid + 1;
            }else if(nums[mid] > target){
                high = mid - 1;
            }
        }
        return -1;
    }
}

你可能感兴趣的:(LeetCode刷题集,leetcode,二分法)