其他分享
首页 > 其他分享> > 剑指 Offer 53 - I. 在排序数组中查找数字 I

剑指 Offer 53 - I. 在排序数组中查找数字 I

作者:互联网

package leetcode;

public class offer_53 {
    public int search(int[] nums, int target) {
        int i=0;
        int j=nums.length-1;
        //target超出范围或者nums为空
        if(nums.length<1||target>nums[j]||target<nums[0]) {return 0;}
        while(i<=j) {
            //双指针,如果头指针找到target,再从尾指针找开始找,个数即为两个坐标的差加一
            if(nums[i]==target) {
                if(nums[j]==target) {
                    return j-i+1;
                }
                else {
                    j=j-1;
                }
            }else {
                i=i+1;
            }
        }
        return 0;
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        offer_53 off=new offer_53();
        int[] nums= {5,7,7,8,8,10};
        System.out.println(off.search(nums, 8));
    }

}

 

标签:超出范围,target,nums,int,Offer,53,查找,public
来源: https://www.cnblogs.com/Yshun/p/15967412.html