求教,一道面试中的Java编程题目,大家帮个忙!

2024-11-30 20:07:28
推荐回答(3个)
回答1:

import java.util.Arrays;
import java.util.Comparator;

public class A {
public static void main(String[] args) {
String[] ls={"A","B","C","V","G","H","K"};
final String[] ses={"B","G","K"};
Arrays.sort(ls, new Comparator(){
public int compare(String str1, String str2) {
if(str1.equals(str2)){
return 0;
}

if(str1.equals(ses[0])){
return -1;
}else if(str1.equals(ses[1])){
if(str2.equals(ses[0])){
return 1;
}

return -1;
}else if(str1.equals(ses[2])){
if(str2.equals(ses[0]) || str2.equals(ses[1])){
return 1;
}

return -1;
}else if(str2.equals(ses[0]) || str2.equals(ses[1]) || str2.equals(ses[2])){
return 1;
}

return 0;

}

});

for(String item: ls){
System.out.println(item);
}
}
}

回答2:

import java.util.ArrayList;
public class Test{

public static void main(String[] args){
new Test();
}

public Test(){
String[] ls={"A","B","C","V","G","H","K"};
String[] ses={"B","G","K"};
String[] result=sortArray(ls,ses);
for(int i=0;i System.out.println(result[i]);
}
}

public String[] sortArray(String[] ls,String[] ses){
ArrayList commonList=new ArrayList();
int[] sesArray=new int[ses.length];
for(int i=0;i sesArray[i]=0;
}
int index;

for(int i=0;i index=arrayStrIndex(ses,ls[i]);
if(index!=1){
sesArray[index]+=1;
}else{
commonList.add(ls[i]);
}
}
String[] resultArray=new String[ls.length];
int aIndex=0;
for(int i=0;i if(sesArray[i]==0){
continue;
}
for(int j=0;j resultArray[aIndex]=ses[i];
aIndex++;
}
}
for(int i=aIndex;i resultArray[i]=commonList.get(i-aIndex);
}
return resultArray;

}

public int arrayStrIndex(String[] pArray,String pStr){
for(int i=0;i if(pArray[i].equals(pStr)){
return i;
}
}
return -1;
}
}
是不是有点多啊?我在网吧,没有java环境,希望没有语法错误呀。应该能够实现功能的。可以自己编译一下。

回答3:

import java.util.ArrayList;
import java.util.List;

public class TestXu {
public static void main(String[] args) {

String[] ls={"A","B","C","V","G","H","K"};
String[] ses={"B","G","K"};

List list = new ArrayList();
boolean flag = false;

for (int i = 0; i < ses.length; i++)
{
for (int j = 0; j < ls.length; j++)
{
if(ses[i].equals(ls[j])) flag = true;
}
if(flag)
{
list.add(ses[i]);
}
flag = false;
}
for (int i = 0; i < ls.length; i++)
{
for (int j = 0; j < list.size(); j++)
{
if (ls[i].equals(list.get(j)))
{
flag = true;
}
}
if(!flag)
{
list.add(ls[i]);
}
flag = false;
}
for (int i = 0; i < list.size(); i++)
{
ls[i] = (String)list.get(i);
}
for(String lsNew : ls)
{
System.out.println(lsNew);
}
}
}