http://www.timl.id.au/?p=23
第二题是sort a deck of card,要求比nlogn更快,然后想法就是根据花色和大小确定牌应该在的位置,然后swap,比如一张牌suite a,rank b,那么它应该在 a*13+b 的位置上。。。然后lz就傻逼了,换回来的之后直接 i++了。。。应该继续判断是否要交换牌直到该位置的牌正确为止。。。.
https://gist.github.com/bookybooky/d79a868a4ce7a891afcc85e6744ffb72
应该可以用桶排序o(n)解决
第二题是sort a deck of card,要求比nlogn更快,然后想法就是根据花色和大小确定牌应该在的位置,然后swap,比如一张牌suite a,rank b,那么它应该在 a*13+b 的位置上。。。然后lz就傻逼了,换回来的之后直接 i++了。。。应该继续判断是否要交换牌直到该位置的牌正确为止。。。.
应该可以用桶排序o(n)解决
- public class SortDeckOfCard {
- static class Card {
- int suite;
- int rank;
- public Card(int suite, int rank) {
- this.suite = suite;
- this.rank = rank;
- }
- }
- public static void sortDeckOfCard(Card[] cards) {
- if (cards == null || cards.length == 0) {
- return;
- }
- for (int i = 0; i < cards.length;) {
- int index = cards[i].suite * 13 + cards[i].rank;
- if (index >= 0 && index < 52
- && (cards[index].suite * 13 + cards[index].rank != index)) {
- Card tmp = cards[index];
- cards[index] = cards[i];
- cards[i] = tmp;
- } else {
- i++;
- }
- }
- }
- public static void main(String[] args) {
- Card[] cards = new Card[52];
- for (int i = 0; i < 4; i++) {
- for (int j = 0; j < 13; j++) {
- cards[51 - i * 13 - j] = new Card(i, j);
- }
- }
- for (int i = 0; i < 52; i++) {
- System.out.print((cards[i].suite * 13 + cards[i].rank) + " ");
- }
- System.out.println();
- sortDeckOfCard(cards);
- for (int i = 0; i < 52; i++) {
- System.out.print((cards[i].suite * 13 + cards[i].rank) + " ");.
- }
- }
- }