zoukankan      html  css  js  c++  java
  • CCF201612-1 中间数(二分思想)

    问题链接:CCF201612试题

    .对n个数进行排序,找出中间那个数,然后将中间那个数的左右与其相等的数去掉,看左右剩下的数个数是否相等,如果相等则中间那个数就是答案,否在输出-1。

    问题描述

    问题描述
    试题编号: 201612-1
    试题名称: 中间数
    时间限制: 1.0s
    内存限制: 256.0MB
    问题描述:
    问题描述
      在一个整数序列a1a2, …, an中,如果存在某个数,大于它的整数数量等于小于它的整数数量,则称其为中间数。在一个序列中,可能存在多个下标不相同的中间数,这些中间数的值是相同的。
      给定一个整数序列,请找出这个整数序列的中间数的值。
    输入格式
      输入的第一行包含了一个整数n,表示整数序列中数的个数。
      第二行包含n个正整数,依次表示a1a2, …, an
    输出格式
      如果约定序列的中间数存在,则输出中间数的值,否则输出-1表示不存在中间数。
    样例输入
    6
    2 6 5 6 3 5
    样例输出
    5
    样例说明
      比5小的数有2个,比5大的数也有2个。
    样例输入
    4
    3 4 6 7
    样例输出
    -1
    样例说明
      在序列中的4个数都不满足中间数的定义。
    样例输入
    5
    3 4 6 6 7
    样例输出
    -1
    样例说明
      在序列中的5个数都不满足中间数的定义。
    评测用例规模与约定
      对于所有评测用例,1 ≤ n ≤ 1000,1 ≤ ai ≤ 1000。
     
    代码:
     
     1 package _201612;
     2 import java.util.Arrays;
     3 import java.util.Scanner;
     4 /**
     5  *     中间数
     6  */
     7 public class Solution1{
     8     public static void main(String[] args) {
     9         Scanner in=new Scanner(System.in);
    10         int [] arr=new int[in.nextInt()];
    11         for (int i = 0; i < arr.length; i++) {
    12             arr[i]=in.nextInt();
    13         }
    14         int max=0;
    15         int min=0;
    16         int s=0;
    17         Arrays.sort(arr);
    18         max=lower_bound(arr, 0, arr.length, arr[arr.length/2]);
    19         min=upper_bound(arr, 0, arr.length, arr[arr.length/2]);
    20         if(arr.length-min==max){
    21             System.out.print(arr[arr.length/2]);
    22         }else{
    23             System.out.print("-1");
    24         }
    25     }
    26 
    27     public static int lower_bound(int a[],int left,int right,int val){
    28         while(left<right){
    29             int mid=left+(right-left)/2;
    30             if(a[mid]>=val){
    31                 right=mid;
    32             }else{
    33                 left=mid+1;
    34             }
    35         }
    36         return left;
    37     }
    38     
    39     public static int upper_bound(int a[],int left,int right,int val){
    40         while(left<right){
    41             int mid=left+(right-left)/2;
    42             if(a[mid]>val){
    43                 right=mid;
    44             }else{
    45                 left=mid+1;
    46             }
    47         }
    48         return left;
    49     }
    50 }
     
     
  • 相关阅读:
    JavaScript 本地对象、内置对象、宿主对象
    数据交换格式
    网页设计之内容、结构、表现分离
    Web前端浏览器兼容初探
    javascript call()与apply()
    天气API
    display:inline,display:inline-block,display:block 区别
    javascript sort()与reverse()
    The Primo ScholarRank Technology: Bringing the Most Relevant Results to the Top of the List
    IOS ——OC—— NSMutableDictionary的使用总结
  • 原文地址:https://www.cnblogs.com/dgwblog/p/10021929.html
Copyright © 2011-2022 走看看