如何比较我的数组列表中的每个元素,以找到两个数组中第n小的元素?

huangapple 未分类评论47阅读模式
英文:

How to compare each element in my arraylist to find the nth smallest of the two arrays?

问题

import java.util.*;

public class Main {

    public static void main(String[] args) {
        System.out.println("请输入一个数作为 n 的值:");
        Scanner sc = new Scanner(System.in);
        System.out.print("n= ");
        int value = sc.nextInt();
        System.out.println();

        Random rand = new Random();
        ArrayList<Integer> setA = new ArrayList<Integer>();
        for (int i = 0; i < value; i++) {
            int picks = rand.nextInt(1000);
            setA.add(picks);
        }
        Collections.sort(setA);
        System.out.println(setA);

        ArrayList<Integer> setX = new ArrayList<Integer>();
        for (int k = 0; k < value; k++) {
            int picks = rand.nextInt(1000);
            setX.add(picks);
        }
        Collections.sort(setX);
        System.out.println(setX);
        solution(setA, setX, value);
    }

    private static int solution(ArrayList<Integer> A1, ArrayList<Integer> X1, int value) {
        ArrayList<Integer> setF = new ArrayList<Integer>();
        for (int c = 0; c < A1.size(); c++) {
            for(int k = 0; k < X1.size(); k++) {
                if(A1.get(c) < X1.get(k)) {
                    setF.add(A1.get(c));
                    break;
                }
            }
        }

        System.out.print(setF);
        return value;
    }
}

请注意,为了简化翻译,我保留了变量名和注释中的英文内容。如果需要完全的中文代码,你可以用中文进行相应的命名和注释。

英文:
import java.util.*;

public class Main {

	public static void main(String[] args) {
		// this section of code will require user input to have the value of n to be set
		System.out.println((&quot;What number would you like to set n equal to ?&quot;));
		Scanner sc = new Scanner(System.in);
		System.out.print((&quot;n= &quot;));
		int value = sc.nextInt();
		System.out.println((&quot;&quot;));

		// this section of code set the two array only to hold the value of n
		Random rand = new Random();
		ArrayList&lt;Integer&gt; setA = new ArrayList&lt;Integer&gt;();
		for (int i = 0; i &lt; value; i++) {
			int picks = rand.nextInt(1000);
			setA.add(picks);
		}
		Collections.sort(setA);
		System.out.println(setA);


		ArrayList&lt;Integer&gt; setX = new ArrayList&lt;Integer&gt;();
		for (int k = 0; k &lt; value; k++) {
			int picks = rand.nextInt(1000);
			setX.add(picks);
		}
		Collections.sort(setX);
		System.out.println(setX);
		solution(setA,setX,value);
	}

	private static int solution(ArrayList&lt;Integer&gt; A1, ArrayList&lt;Integer&gt; X1, int value) {
		// This section of code is where the arrays will be compared to find the nth smallest.
		ArrayList&lt;Integer&gt; setF = new ArrayList&lt;Integer&gt;();
		for (int c = 0; c &lt; A1.size(); c++) {
			for(int k = 0; k &lt; X1.size(); k++) {
				if(A1.get(c) &lt; X1.get(k)) {

				}
			}
		}

		System.out.print(setF);
		return value;
	}
}

So far i have my program set up to have the user enter a number that will be used for the size of the array. Once the number has been entered the arrays are created with random numbers that will be place in order. Next I would like to go through each element of my arrays and compare to see which numbers can be placed in my Final array. In my final array is the nth smallest number which will be return. I can not merge the two array together.

For example if n = 10 below are my two arrays

> A [124, 264, 349, 450, 487, 641, 676, 792, 845, 935]

> B [2, 159, 241, 323, 372, 379, 383, 475, 646, 836]

124 < 2 this statement is false so 2 would get added to my final array list. Array B should move to the next element in the list.
124 < 159 this is true so 124 gets added to my final array list. Array A should move to the next element in the list.
264 < 159 this statement is false so 159.

Final Array [2,124, 159,...]

n smallest is 383.

Hopefully that example gives you an ideal of what I'm trying to accomplish.if you have something better let me know please..

答案1

得分: 0

你的解决方案是可行的,但你可以将解决方案的时间复杂度从O(n^2)优化为O(n)。

你可以这样做,由于数组已经是等量排序的,你可以比较两个数组中位置0的元素(就像你正在做的那样),然后选择较小的元素,将该元素从数组中弹出并添加到最终数组中。继续测试索引为0的元素,直到其中一个数组为空为止。一旦一个数组为空,你可以将另一个数组的剩余部分追加到最终数组的末尾,这样就可以达到你想要的效果。

因此,以下是一些Java代码实现:

private ArrayList<Integer> sortTwoArrays(ArrayList<Integer> arrayA, ArrayList<Integer> arrayB) {
    ArrayList<Integer> finalArray = new ArrayList<>();
    while (!arrayA.isEmpty() && !arrayB.isEmpty()) {
        if (arrayA.get(0) < arrayB.get(0)) {
            // 移除元素并存储
            finalArray.add(arrayA.remove(0));
        } else {
            finalArray.add(arrayB.remove(0));
        }
    }

    // 找出哪个数组不为空
    // 将非空数组的剩余内容添加到finalArray的末尾
    if (!arrayA.isEmpty()) {
        finalArray.addAll(arrayA);
    } else if (!arrayB.isEmpty()) {
        finalArray.addAll(arrayB);
    }

    return finalArray;
}

要获得第n小的值,只需将用户传入函数的值添加到函数的参数中,然后在返回函数时,只需返回finalArray.get(nthIndex)

示例代码展示在这里

注意:此方法会破坏原始的两个ArrayList

如果你想保留这两个数组,我建议在变量中跟踪两个列表中的索引,并根据一个项目是否小于另一个项目来增加索引。此外,在while循环后更改if语句的检查方式,从isEmpty()检查更改为比较,例如indexOfArrayA == arrayA.size() - 1。

希望这能以某种方式帮助你。

英文:

Your solution would work but you can make your solution's time complexity o(n) rather than o(n^2).

What you could do is, since the arrays are equally sorted, you can compare both elements at position zero (like you're doing) and then whichever element is smaller, pop that element from the array and add it to the final array. Keep testing the zero(th) indexed element until one of the arrays is empty. Once its empty, you can just append the remaining other array on the end of the final array and that should achieve what you want.

So in some java code implementation:

private ArrayList&lt;Integer&gt; sortTwoArrays(ArrayList&lt;Integer&gt; arrayA, ArrayList&lt;Integer&gt; arrayB) {
    ArrayList&lt;Integer&gt; finalArray = new ArrayList&lt;&gt;();
    while(!arrayA.isEmpty() &amp;&amp; !arrayB.isEmpty()) {
        if (arrayA.get(0) &lt; arrayB.get(0)) {
            // remove element and store
            finalArray.add(arrayA.remove(0));
        }
        else {
            finalArray.add(arrayB.remove(0));
        }
    }

    // Find out which array is not empty
    // Adds remaining contents of non-empty array to end of finalArray
    if (!arrayA.isEmpty()) {
        finalArray.addAll(arrayA);
    }
    else if (!arrayB.isEmpty()) {
        finalArray.addAll(arrayB);
    }

    return finalArray;
}

To get the nth smallest value, just add the value the user passes in as an argument to the function and then when you're returning the function, just return finalArray.get(nthIndex)

Example code showcase here.

> Note: The original two ArrayLists will get destroyed from this method
>
> If you want preserve the two arrays, I recommend keeping track of both indexes in the list inside variables and then incrementing based on when one item is less than another. Additionally, change the If statement check after the whie-loop from an isEmpty() check to a comparison like so indexOfArrayA == arrayA.size() - 1.

I hope this helps in anyway.

huangapple
  • 本文由 发表于 2020年4月5日 04:48:43
  • 转载请务必保留本文链接:https://java.coder-hub.com/61034581.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定