脚本宝典收集整理的这篇文章主要介绍了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:
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,请注明来意。