Java 两个随机数组之间的最小值?
给定两个长度为5个整数的随机数组(每个整数的最大值为6),我需要一个函数来比较哪个数组的整数最小。如果两个数组具有相同的最低整数,则函数将比较下两个最低整数,依此类推。对于smallestOfTwo(),我能想到的唯一方法就是占用数百行数据和太多内存。以下是我目前仅有的一点:Java 两个随机数组之间的最小值?,java,arrays,comparison,Java,Arrays,Comparison,给定两个长度为5个整数的随机数组(每个整数的最大值为6),我需要一个函数来比较哪个数组的整数最小。如果两个数组具有相同的最低整数,则函数将比较下两个最低整数,依此类推。对于smallestOfTwo(),我能想到的唯一方法就是占用数百行数据和太多内存。以下是我目前仅有的一点: public static void main(String[] args) { int[] n= new int [5]; int[] m= new int [5]; for(int i=0;
public static void main(String[] args) {
int[] n= new int [5];
int[] m= new int [5];
for(int i=0; i<n.length; i++) {
n[i]=(int) (Math.random() * 6) + 1;
}
for(int x=0;x<n.length;x++) {
m[x]=(int) (Math.random() * 6) + 1;
}
System.out.println(smallestOfTwo(n,m)+" has the smallest value of the two arrays");
}
public static String smallestOfTwo(int[] x,int[] y) {
String smallest = "unassigned";
//help??
if() {
smallest = "Array n"
}
else
smallest = "Array m"
return smallest;
}
publicstaticvoidmain(字符串[]args){
int[]n=新的int[5];
int[]m=新的int[5];
对于(int i=0;i使用冒泡排序按降序对数组进行排序,查找两者中的最后一个索引。现在您必须比较这两个索引。您可以使用arrays类,它有一个静态排序方法
Ex: int arr[]={5,3,2,1};
Arrays.sort(arr);
将对新数组进行排序,并根据需要选择第一个或最后一个(最大或最小)
您可以在此站点中看到数组方法
您可以首先对数组进行排序,这将使手头的任务比简单地循环数组并比较它们的值更容易解决
public static String smallestOfTwo(int[] n,int[] m)
{
Arrays.sort(n);
Arrays.sort(m);
for (int i = 0; i < n.length; i++) {
if(n[i] < m[i]){
return "Array n";
}else if(n[i] > m[i]){
return "Array m";
}
}
return "both Array n & Array m are the same";
}
公共静态字符串smallestOfTwo(int[]n,int[]m)
{
数组。排序(n);
数组。排序(m);
for(int i=0;im[i]){
返回“数组m”;
}
}
返回“数组n和数组m都相同”;
}
对数组进行排序,按字典顺序进行比较。如果在检查每个数组中的最小元素之前对数组进行排序,这将是最简单的方法。“数百行代码”“有代码< >数组。排序< /代码>我真的很抱歉,我认为这是C++帖子。我的坏消息,谢谢你的评论!”合作伙伴很高兴它有帮助。如果解决了你的问题^ ^ ^不要忘记标记为接受。