1. 程式人生 > >Leetcode 703.Kth Largest Element in a Stream

Leetcode 703.Kth Largest Element in a Stream

Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element.

Your KthLargest class will have a constructor which accepts an integer k and an integer array nums, which contains initial elements from the stream. For each call to the method KthLargest.add, return the element representing the kth largest element in the stream.

Example:

int k = 3;
int[] arr = [4,5,8,2];
KthLargest kthLargest = new KthLargest(3, arr);
kthLargest.add(3); // returns 4
kthLargest.add(5); // returns 5
kthLargest.add(10); // returns 5
kthLargest.add(9); // returns 8
kthLargest.add(4); // returns 8

Note:
You may assume that nums’ length ≥ k-1 and k ≥ 1.

題目大意:
設計一個類KthLargest ,它可以儲存一組數字,要求能夠返回這組數從大到小的第K個數。比如 k = 3; int[] arr = [4,5,8,2]; 排序後是[8,5,4,2],從大到小的第3個數字是4;

通過這道題我想練習一下插入排序及連結串列,思路如下:

首先在構造方法中,將arr排序,並構造一個雙向連結串列,連結串列中的每一個節點對應arr中的每一個元素。然後利用插入排序的思想,向連結串列中新增數字。最後從頭掃描連結串列,返回第K大的數。


import java.util.Arrays;

class KthLargest {

    // 連結串列中的節點
    class
Node { Node pre = null; Node next = null; int val; Node(int val) { this.val = val; } } private int k; private Node head = new Node(-1); public KthLargest(int k, int[] nums) { this.k = k; Node h = head; Arrays.sort(nums); // 排序 // 構造連結串列 for(int i = nums.length-1; i >= 0; i--) { Node n = new Node(nums[i]); h.next = n; n.pre = h; h = h.next; } } public int add(int val) { Node h = head.next; if(h == null) { // 當連結串列為空時,插入一個頭節點 h = new Node(val); head.next = h; h.pre = head; return find(); } while(h != null) { if(val > h.val) { // 將節點插入到連結串列中 Node node = new Node(val); h.pre.next = node; node.pre = h.pre; node.next = h; h.pre = node; break; } if(h.next == null) { // 將節點插入到連結串列尾 h.next = new Node(val); h.next.pre = h; break; } h = h.next; } return find(); } // 找到第K大的數字 private int find() { int i = 1; Node h = head.next; while(i < k && h != null) { h = h.next; i++; } return h.val; } public static void main(String[] args) { int k = 2; int[] arr = {0}; KthLargest kthLargest = new KthLargest(k, arr); System.out.println(kthLargest.add(-1)); System.out.println(kthLargest.add(1)); System.out.println(kthLargest.add(-2)); System.out.println(kthLargest.add(-4)); System.out.println(kthLargest.add(3)); } }

執行這個小例子,每一步連結串列中的數字如下:
【0】
【0、-1】
【1、0、-1】
【1、0、-1、-2】
【1、0、-1、-2、-4】
【3、1、0、-1、-2、-4】
輸出如下:
在這裡插入圖片描述