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

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

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;
    }
}
全部评论

相关推荐

评论
点赞
收藏
分享
牛客网
牛客企业服务