378. Kth smallest Element in a Sorted Matrix (Java, priority queue)

Source: Internet
Author: User
Tags comparable

Topic:

Given a n x n Matrix where each of the rows and columns is sorted in ascending order, find the kth smal Lest element in the matrix.

Example:

Matrix = [   1,  5,  9],   [Ten, one, +],   [, A,= 8,  return 13.

Analysis: using priority queue, custom comparison rules, so that the smallest elements ranked in the first team.

Code:

//priority queue, a new data structure interface that is provided starting from jdk1.5//If comparator is not provided, the elements in the priority queue are sorted by default in natural order//The element with the highest priority is removed from the queue each time. ImportJava.util.PriorityQueue;/*** Known as a n*m matrix, each row, each column is ordered. * Ask for a small element of k in this matrix *@authori333083 **/ Public classKthsmallesteleinsortedmatrix { Public Static voidMain (string[] args) {//TODO auto-generated Method Stub        int[] A =New int[][]{{1,5,9,11},{2,6,10,14},{3,7,13,15}}; System.out.println (Kthsmallest (A,11)); }        //to find the element K small in the matrix     Public Static intKthsmallest (int[] Matrix,intk) {        introws = matrix.length;//number of rows in the matrix        intcols = Matrix[0].length;//Number of columns//Priority Queuepriorityqueue<tuple> queue =NewPriorityqueue<tuple> ();//into the queue                /*** Here is a very ingenious design place, the first line ascending sequence first into the queue, according to the definition of the tuple type, the smallest element will be at the head of the team. * Whenever the first element of the team is out of the queue, the next element of its column is queued until the last row; * This allows you to compare the same row of an element with the smaller of the adjacent elements in the same column, ensuring that the first element is always the minimum of all elements in the matrix*/         for(intj = 0; J < cols; ++j) Queue.add (NewTuple (0,j,matrix[0][j])); //carry out K-1, team, the last team first element must be all elements of the K small         for(inti = 0; i < k-1; ++i) {Tuple P= Queue.poll ();//out QueueSystem.out.print (P.val + ""); if(p.x = = rows-1)//In the end, no element needs to be queued.                Continue; Queue.add (NewTuple (p.x + 1,p.y,matrix[p.x + 1][p.y])); }                returnQueue.poll (). Val; }}//implement the comparable interface to overwrite the CompareTo method, implement the comparison in the CompareTo method//Customizing a data structure-tuple, inheriting from comparable interfaceclassTupleImplementsComparable<tuple>{    intx; inty; intVal;  PublicTuple (intXintYintval) {         This. x =x;  This. y =y;  This. val =Val; } @Override Public intcompareTo (Tuple t) {return  This. Val-t.val;//if the newly added element is smaller, it will be ranked in the first    }}

378. Kth smallest Element in a Sorted Matrix (Java, priority queue)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.