题解 | #二分查找-I#

二分查找-I

https://www.nowcoder.com/practice/d3df40bd23594118b57554129cadf47b

using System;
using System.Collections.Generic;


class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param nums int整型一维数组 
     * @param target int整型 
     * @return int整型
     */
    public int search (List<int> nums, int target) {
        if( nums.Count == 1 ){
            if(nums[0] == target){
               return 0;
            }
            else{
                return -1;
            }
        }

        int left = 0, right = nums.Count -1;

        while(left <= right){
            int leftNum = nums[left];
            int rightNum = nums[right];

            if(leftNum == target){
                return left;
            }else if (rightNum == target)
            {
                return right;
            }else{
                left ++;
                right --;
            }
        } 
        return -1;
    }
}

全部评论

相关推荐

09-12 11:55
已编辑
湖南工商大学 Java
那一天的Java_J...:这种一堆问题的,别去
点赞 评论 收藏
分享
09-17 10:53
四川大学 C++
牛客91242815...:会写标书没有任何卵用,鉴定为横向垃圾导师的受害者
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务