英文:
Check if some variables in an array are equal and then assign those to another array
问题
我有这个一维数组,包含4个值。
例如:
moves[] = { 2, 2, 3, 3 };
我希望能够检查数组中每个相等且最小的值。所以最终我希望我的新数组看起来是这样的:
moves1[] = {2, 2};
如何在Java中实现这个?
英文:
I have this one-dimensional array, that holds 4 values.
For example:
moves[] = { 2, 2, 3, 3 };
I want to be able to check each value in the array that is equal and the smallest. So at the end I want my new array to be like this:
moves1[] = {2, 2};
How can I achieve this in Java?
答案1
得分: 0
循环遍历数组,在每次遇到新的较小值时,重置结果列表:
public static void main(String[] args) {
int moves[] = { 2, 2, 3, 3 };
int lowest = Integer.MAX_VALUE;
List<Integer> low = new ArrayList<>();
for (int i = 0; i < moves.length; i++) {
if (moves[i] < lowest) {
low = new ArrayList<>();
lowest = moves[i];
}
if (moves[i] == lowest)
low.add(moves[i]);
}
Integer[] result = low.toArray(new Integer[low.size()]);
}
英文:
Loop through the array, each time you encounter a new lower value, reset the result list:
public static void main(String[] args) {
int moves[] = { 2, 2, 3, 3 };
int lowest=Integer.MAX_VALUE;
List<Integer> low=new ArrayList<>();
for(int i=0;i<moves.length;i++) {
if(moves[i]<lowest)
{
low=new ArrayList<>();
lowest=moves[i];
}
if (moves[i]==lowest)
low.add(moves[i]);
}
Integer[] result=low.toArray(new Integer[low.size()]);
}
答案2
得分: 0
以下解决方案不假设数组已排序,并且运行时复杂度为 O(n)
。此外,它的内存占用非常低,因为它不会创建数组的副本来进行排序。
public static int[] smallestAndEqual(int[] arr) {
if (arr.length == 0) {
return new int[0]; // 如果需要,可以缓存此结果
}
int smallest = Integer.MAX_VALUE;
int count = 0;
for (int i : arr) {
if (i < smallest) {
smallest = i;
count = 1;
} else if (i == smallest) {
count++;
}
}
int[] ints = new int[count];
Arrays.fill(ints, smallest);
return ints;
}
示例:
public static void main(String[] args) {
int[] ints = {2, 2, 3, 3};
int[] result = smallestAndEqual(ints);
System.out.println(Arrays.toString(result));
}
执行此示例时,输出为:
[2, 2]
英文:
The following solution does not assume that the array is sorted and has a runtime complexity of O(n)
. Furthermore it has a very low memory footprint, since it does not create a copy of the array to sort it.
public static int[] smallestAndEqual(int[] arr) {
if (arr.length == 0) {
return new int[0]; // can be cached if needed
}
int smallest = Integer.MAX_VALUE;
int count = 0;
for (int i : arr) {
if (i < smallest) {
smallest = i;
count = 1;
} else if (i == smallest) {
count++;
}
}
int[] ints = new int[count];
Arrays.fill(ints, smallest);
return ints;
}
An example:
public static void main(String[] args) {
int[] ints = {2, 2, 3, 3};
int[] result = smallestAndEqual(ints);
System.out.println(Arrays.toString(result));
}
Which outputs the following line when executed:
[2, 2]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论