首页 > 试题广场 >

查找第K大的元素

[编程题]查找第K大的元素
  • 热度指数:11087 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
给定一个无序的整型数组A[n],数组大小大于等于3,允许有值相同的元素;请设计算法找到该数组排序后第三大的元素值并输出.

输入描述:
一个非空的整数数组(至少有3个元素,可正可负)


输出描述:
第三大的元素值
示例1

输入

[1,2,3,4,5]

输出

3
示例2

输入

[1,1,2,2,3]

输出

2
示例3

输入

[6,5,4,4,1,2]

输出

4

第一次使用ACM模式,真难受

我就偷个懒,直接解析字符串数字,不要数组了

import java.util.Scanner;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.io.PrintWriter;
import java.io.OutputStreamWriter;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
     public static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
     public static PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));

     public static void main(String[] args) throws Exception {

        String s = reader.readLine();
        if( s!=null) {
            out.println(parseIntArray(s));
        }
        out.flush();
    }

    public static int parseIntArray(String s) {
        int mx1 = Integer.MIN_VALUE;
        int mx2 = Integer.MIN_VALUE;
        int mx3 = Integer.MIN_VALUE;
        int base = 0;
        int deep = 0;
        int isNeg = 0;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == '\n' || c == '\t' || c == '\f' || c == '\r' || c == ' ')
                continue;
            switch (c) {
            case '[':
                base = 0; // 初始化
                deep++;
                break;
            case ']':
                deep--;
                if (deep == 0) {
                    if (isNeg > 0) {
                        base *= -1;
                        isNeg--;
                    }
                    if ( mx1 < base) {
                        mx3 = mx2;
                        mx2 = mx1;
                        mx1 = base;
                    } else if ( mx2 < base ) {
                        mx3 = mx2;
                        mx2 = base;
                    } else if ( mx3 < base ) {
                        mx3 = base;
                    }
                }
                break;
            case '-':
                isNeg++;
                break;
            case ',':
                if (isNeg > 0) {
                    base *= -1;
                    isNeg--;
                }
                // arr[size++] = base;
                if ( mx1 < base) {
                    mx3 = mx2;
                    mx2 = mx1;
                    mx1 = base;
                } else if ( mx2 < base ) {
                    mx3 = mx2;
                    mx2 = base;
                } else if ( mx3 < base ) {
                    mx3 = base;
                }
                base = 0;
                break;
            default:
                if( c >= '0' && c <= '9') {
                    base = base * 10 + c - '0';
                }

                break;
            }
        }
        return mx3;
    }
}
编辑于 2024-03-05 00:22:08 回复(0)
import java.util.Scanner;
import java.util.Arrays;
public class Main{
    public static void main(String[] args){
        Scanner input=new Scanner(System.in);
        String[] str=input.nextLine().replace("[","").replace("]","").split(",");
        int strInt[]=new int[str.length];
        for(int i=0;i<str.length;i++){
            strInt[i]=Integer.parseInt(str[i]);
        }
        Arrays.sort(strInt);
        System.out.println(strInt[strInt.length-3]);
    }
}
利用Arrays类的sort方法轻松解决
发表于 2020-03-18 15:52:28 回复(2)
基于快速排序的方法
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String[] strings = in.nextLine().replace("[","").
                replace("]","").split(",");
        int[] a = new int[strings.length];
        int n = a.length;
        for (int i=0;i<n;i++)
            a[i] = Integer.parseInt(strings[i]);
        int k = n-3;
        int t = -1;
        int low = 0,high = n-1;
        while (t != k){
            t = partition(a,low,high);
            if (t > k)
                high = t-1;
            else if (t < k)
                low = t+1;
        }
        System.out.println(a[t]);
    }

    public static int partition(int[] a,int low,int high){
        int key = a[low];
        while (low < high){
            while (low < high && key <= a[high])
                high--;
            if (low < high)
                a[low++] = a[high];
            while (low < high && a[low] <= key)
                low++;
            if (low < high)
                a[high--] = a[low];
        }
        a[low] = key;
        return low;
    }
}
在k已确定,且k并不是很大时,可以用这种方法,只需一次遍历
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String[] strings = in.nextLine().replace("[","").
                replace("]","").split(",");
        int[] a = new int[strings.length];
        int n = a.length;
        for (int i=0;i<n;i++)
            a[i] = Integer.parseInt(strings[i]);
        int first = Integer.MIN_VALUE;
        int second = Integer.MIN_VALUE;
        int third = Integer.MIN_VALUE;
        for (int i=0;i<n;i++){
            if (a[i] > first){
                third = second;
                second = first;
                first = a[i];
            }else if (a[i] > second){
                third = second;
                second = a[i];
            }else if (a[i] > third){
                third = a[i];
            }
        }
        System.out.println(third);
    }
}



发表于 2019-08-15 16:30:10 回复(0)
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String str = scanner.next();
        String[] strNumber = str.substring(1, str.length() - 1).split(",");
        int[] number = new int[strNumber.length];
        for (int i = 0; i < strNumber.length; i++) {
            number[i] = Integer.parseInt(strNumber[i]);
        }
        Arrays.sort(number);
        System.out.println(number[number.length -3]);
    }
}
发表于 2019-07-04 17:39:36 回复(0)
package com.newcode;

import java.util.ArrayList;
import java.util.Scanner;

public class Demo1 {
    
    public static void main(String[] args) {
        String str=null;
        int index=0;
        StringBuffer sb=new StringBuffer();
        ArrayList<Integer> al=new ArrayList<>();
        Scanner sc=new Scanner(System.in);
        sb.append(sc.nextLine());
        sb.deleteCharAt(0);
        sb.deleteCharAt(sb.length()-1);
        System.out.println(sb);
        for(int i=0;i<sb.length();i++) {
            if(sb.charAt(i)==',') {
                al.add(Integer.parseInt(sb.substring(index, i)));
                index=i+1;
            }
        }
        al.add(Integer.parseInt(sb.substring(index, sb.length())));
        for(int i=0;i<al.size()-2;i++) {
            for(int j=i+1;j<al.size();j++) {
                if(al.get(i)<al.get(j)){
                    int temp=al.get(i);
                    al.remove(i);
                    al.add(i, al.get(j-1));
                    al.remove(j);
                    al.add(j, temp);
                    }
            }
        }
    System.out.println(al.get(2));
    }
}




发表于 2018-12-12 18:13:00 回复(0)