ACM —— 1007

解题代码:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;

public class Main {

	static class Node implements Comparable {
		
		String str;
		int id;
		int sortN;
		public Node(String str, int id ,int sortN) {
			this.id = id;
			this.sortN = sortN;
			this.str = str;
		}
		
		@Override
		public int compareTo(Object o) {

			Node another = (Node) o;
			if (another.sortN == sortN) {
				return (another.id < id) ? 1 : ((another.id == id) ? 0 : -1);
			} else {
				return (another.sortN < sortN) ? 1 : -1;
			}

		}

	}

	public static void main(String[] args) {
		Scanner stdin = new Scanner(System.in);
		int len = stdin.nextInt();
		int num = stdin.nextInt();
		String dna;
		int sortN;
		List<Node> nodeList = new ArrayList<Node>();
		for (int i = 0; i < num; i ++) {
			dna = stdin.next();
			sortN = getSortN(dna, len);
			nodeList.add(new Node(dna, i, sortN));
		}
		Collections.sort(nodeList);
		for (Iterator<Node> l = nodeList.iterator(); l.hasNext();) {
			System.out.println(l.next().str);
		}
	}

	private static int getSortN(String dna, int len) {

		int sortCount = 0;
		for (int i = 0; i < len; i++) {
			for (int j = i+1; j < len; j++) {
				if (dna.charAt(i) > dna.charAt(j)) {
					sortCount++;
				}
			}
		}
		return sortCount;
		
	}
}

Comparator 和 Comparable

用于对集合对象或数组对象进行排序。

区别 :

1.只要实现Comparable 接口的对象直接就成为一个可以比较的对象,但是需要修改源代码

2.用Comparator 的好处是不需要修改源代码, 而是另外实现一个比较器, 当某个自定义的对象需要作比较的时候,把比较器和对象一起传递过去就可以比大小了, 并且在Comparator 里面用户可以自己实现复杂的可以通用的逻辑,使其可以匹配一些比较简单的对象,那样就可以节省很多重复劳动了。

Iterator

Java中的Iterator功能比较简单,并且只能单向移动:

  (1) 使用方法iterator()要求容器返回一个Iterator。第一次调用Iterator的next()方法时,它返回序列的第一个元素。注意:iterator()方法是java.lang.Iterable接口,被Collection继承。

  (2) 使用next()获得序列中的下一个元素。

  (3) 使用hasNext()检查序列中是否还有元素。

  (4) 使用remove()将迭代器新返回的元素删除。

  Iterator是Java迭代器最简单的实现,为List设计的ListIterator具有更多的功能,它可以从两个方向遍历List,也可以从List中插入和删除元素。

 

猜你喜欢

转载自blog.csdn.net/WYYZ5/article/details/48290837
ACM