题解 | #数字在升序数组中出现的次数#

数字在升序数组中出现的次数

http://www.nowcoder.com/practice/70610bf967994b22bb1c26f9ae901fa2

// 方法一
import java.io.*;
import java.util.*;
import java.util.stream.*;

public class Solution {
    public int GetNumberOfK(int [] array , int k) {
       if(array == null || array.length == 0 || k > array[array.length - 1] || k < array[0]){
           return 0;
       }

       return Arrays.stream(array)
           .boxed()
           .collect(Collectors.toMap(e->e,e->1,Integer::sum))
           .getOrDefault(k,0);
    }
}
// 方法二
import java.io.*;
import java.util.*;
import java.util.stream.*;

public class Solution {
    public int GetNumberOfK(int [] array , int k) {

        if(array == null || array.length == 0 || array[array.length - 1] < k || k < array[0]){
            return 0;
        }

        int pos1 = 0;
        int left = 0, right = array.length - 1;
        while(left + 1 < right){
            int mid = left + (right - left)/2;
            if(array[mid] >= k){
                right = mid;
            }else{
                left = mid;
            }
        }

        if(array[left] == k){
            pos1 = left;
        }else if(array[right] == k){
            pos1 = right;
        }else{
            return 0;
        }

        int pos2 = 0;
        left = 0;
        right = array.length - 1;
        while(left + 1 < right){
            int mid = left + (right - left)/2;
            if(array[mid] <= k){
                left = mid;
            }else{
                right = mid;
            }
        }

        if(array[right] == k){
            pos2 = right;
        }else if(array[left] == k){
            pos2 = left;
        }

        return pos2 - pos1 + 1;
    }
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
11-27 10:46
点赞 评论 收藏
分享
11-24 11:23
门头沟学院 C++
点赞 评论 收藏
分享
面试摇了我吧:啊哈哈面试提前五个小时发,点击不能参加就是放弃
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务