JAVA学习日记----------排序篇03
使用排序容器TreeSet与TreeMap
一.TreeSet:数据元素可以排序且不可重复
去重:比较等于0即重复
1.元素可以排序 java.lang.Comparable重写 compareTo()
new TreeSet()
2.排序业务类 java.util.Comparator 重写compare()
new TreeSet(Comparator<? super E>comparator)
TreeSet在添加数据时排序,数据更改不会影响原来的顺序,使用过程中不要修改数据,可能重复
用final来修饰属性可以避免此问题
TreeSet必须要实现Comparator类(即提供一个比较器)或者Comparable接口,不然会有异常报错
二. TreeMap
与TreeSet的操作一致
使用Collections类中方法
用Collections中的suffle方法实现斗地主洗牌发牌
public static void main(String[] args) {
// TODO Auto-generated method stub
List<Integer> list = new ArrayList<Integer>();
for(int i = 0;i<54;i++){
list.add(i);
}
Collections.shuffle(list);
List<Integer> p1 = new ArrayList<Integer>();
List<Integer> p2 = new ArrayList<Integer>();
List<Integer> p3 = new ArrayList<Integer>();
List<Integer> last = new ArrayList<Integer>();
for(int i =0;i<51;i+=3 ){
p1.add(list.get(i));
p2.add(list.get(i+1));
p3.add(list.get(i+2));
}
last.add(list.get(51));
last.add(list.get(52));
last.add(list.get(53));
System.out.println("第一个人:"+p1);
System.out.println("第一个人:"+p2);
System.out.println("第一个人:"+p3);
System.out.println("底牌为"+last);
}
今天的TOPCODER
//SRM 147 DIV 2 250
Problem Statement | |||||||||||||
Julius Caesar used a system of cryptography, now known as Caesar Cipher, which shifted each letter 2 places further through the alphabet (e.g. 'A' shifts to 'C', 'R' shifts to 'T', etc.). At the end of the alphabet we wrap around, that is 'Y' shifts to 'A'. We can, of course, try shifting by any number. Given an encoded text and a number of places to shift, decode it. For example, "TOPCODER" shifted by 2 places will be encoded as "VQREQFGT". In other words, if given (quotes for clarity) "VQREQFGT" and 2 as input, you will return "TOPCODER". See example 0 below. | |||||||||||||
Definition | |||||||||||||
| |||||||||||||
Limits | |||||||||||||
| |||||||||||||
Constraints | |||||||||||||
- | cipherText has between 0 to 50 characters inclusive | ||||||||||||
- | each character of cipherText is an uppercase letter 'A'-'Z' | ||||||||||||
- | shift is between 0 and 25 inclusive |
public class CCipher {
public String decode(String cipherText,int shift){
char[] cipherTexts = cipherText.toCharArray();
char[] cipherTextsNew = new char[cipherTexts.length];
for(int i = 0;i<cipherTexts.length;i++){
if(cipherTexts[i]-shift<65){
cipherTextsNew [i] = (char) (cipherTexts[i]+26-shift);
}else
{
cipherTextsNew [i] = (char) (cipherTexts[i]-shift);
}
}
return String.valueOf(cipherTextsNew);
}
}
今天学到的,通过toCharArray()方法将String转char[],然后通过valueOf()方法将char[]转String