求教,中软java笔试的一道题?
给定如下数组:
String[] ls={"A","B","C","V","G","H","K"};
String[] ses={"B","G","K"};
要求参照数组ses中的字母顺序对数组ls进行优先排序,对没有在ses数组中出现的字母排在数组的最后,不用排序,最后输出排好顺序的数组ls.
请大神指教~ 中软 中软卓越 java
[解决办法]
如果说ses数组里的元素在ls中都有的话
String[] ls={"A","B","C","V","G","H","K"};
String[] ses={"B","G","K"};
List<String> list1=new LinkedList<String>(Arrays.asList(ls));
List<String> list2=Arrays.asList(ses);
list1.removeAll(list2);//移除list1中存在的list2的元素
list1.addAll(0, list2);//再把这些元素放到首位
ls=list1.toArray(new String[list1.size()]);
System.out.println(Arrays.toString(ls));
public static void main(String[] args) {
String[] ls = { "A", "B", "C", "V", "G", "H", "K" };
String[] ses = { "B", "G", "K" };
sort(ls,ses);
}
private static void sort(String[] ls,String[] ses) {
Map<String,Integer> map = new LinkedHashMap<String,Integer>();
for (String s : ses) {
map.put(s, 0);
}
for (String s : ls) {
map.put(s, 1);
}
LinkedList<String> list = new LinkedList<String>();
for (String key : map.keySet()) {
if(map.get(key) > 0) list.add(key);
}
System.out.println(list);
}