在排序数组中,找出给定数字的出现次数.比如 [1, 2, 2, 2, 3] 中2的出现次数是3次。

来源:互联网 发布:中检网络在线培训官网 编辑:程序博客网 时间:2024/05/17 17:58

import java.util.Scanner;

//在排序数组中,找出给定数字的出现次数.比如 [1, 2, 2, 2, 3] 中2的出现次数是3次。
public class CiShu {

 public static void main(String args[]) {

  int[] nums = new int[] { 1, 2, 2, 2, 2, 3, 3, 3, 5, 5 };

  Scanner cin = new Scanner(System.in);
  int a = cin.nextInt();

  int i = 0;
  while (nums[i] <= a) {
   i++;
   if (i > nums.length - 1)
    break;
  }

  i--;

  System.out.println(i);
  int result = 0;
  while (nums[i] == a) {
   i--;
   result++;
   if (i < 0)
    break;
  }

  System.out.print(result);

 }

}

原创粉丝点击