Home  >  Article  >  Database  >  在排序数组中,找出给定数字的出现次数.比如 [1, 2, 2, 2, 3] 中

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

WBOY
WBOYOriginal
2016-06-07 15:43:191374browse

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 =

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]    i++;
   if (i > nums.length - 1)
    break;
  }

  i--;

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

  System.out.print(result);

 }

}

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn