# 数字在排序数组中出现的次数 HashMap

import java.util.HashMap;
public class SolutionListNode {
public int GetNumberOfK(int[] array, int k) {
HashMap<Integer, Integer> map = new HashMap();

for (int i;=0; i < array.length; i++) {
if (!map.containsKey(array[i])) {
map.put(array[i], 1);
} else {
int count = map.get(array[i]);
map.put(array[i], ++count);
}
}

boolean flag = map.containsKey(k);//判断是否存在key等于k
if (flag == true) {
return map.get(k);//获取key对应的value

}return 0;
}

public static void main(String[] args) {
int [] arr={1,2,3,3,3,3,4,5};
SolutionListNode test=new SolutionListNode();
System.out.println(test.GetNumberOfK(arr,3));
}
}


package pag1;

public class SolutionListNode {
/*二分查找 找到第一个K 和 最后一个K 二者位置相减*/
public int GetNumberOfK(int [] array , int k) {
if(array.length==0)
return 0;
int numbers =0;
int first =GetFirstIndex(array,k,0,array.length-1);
int last = GetLastIndex(array,k,0,array.length-1);
if(first>-1 && last>-1)
numbers = last - first +1;
return numbers;
}
int GetFirstIndex(int[]data,int k,int start,int end){
if(start > end)
return -1;
int mid = start+(end-start)/2;
if(data[mid] == k){
if((mid > start && data[mid-1] != k) || mid == start)
return mid;
else
end = mid-1;
}else{
if(data[mid] > k)
end = mid - 1;
else
start = mid + 1;
}
return GetFirstIndex(data,k,start,end);
}
int GetLastIndex(int[]data,int k,int start,int end){
if(start > end)
return -1;
int mid = start+(end-start)/2;
if(data[mid] == k){
if((mid <end && data[mid+1] != k) || mid == end)
return mid;
else
start = mid+1;
}else{
if(data[mid] > k)
end = mid - 1;
else
start = mid + 1;
}
return GetLastIndex(data,k,start,end);
}
public static void main(String[] args) {
int [] arr={3,3,3,3};
SolutionListNode test=new SolutionListNode();
System.out.println(test.GetNumberOfK(arr,3));
}
}


08-24 2985
06-30 118
05-31 40
08-20 30
07-09 1万+
02-24 95
07-10 496
02-22 9817
03-08 1207
07-03 604