相关疑难解决方法(0)

查找数组中总和为指定值的所有整数对

设计一种算法来查找数组中总和为指定值的所有整数对.

我已经尝试使用哈希表来存储数组元素总和的条目,但它不是一个有效的解决方案.

我可以使用什么算法来有效地解决这个问题?

algorithm

24
推荐指数
5
解决办法
4万
查看次数

找到一对数字,其差别是未排序数组中的输入值'k'

正如标题中所提到的,我想找到差异为K的元素对

example k=4 and a[]={7 ,6 23,19,10,11,9,3,15}
output should be :
   7,11
   7,3
   6,10
   19,23
   15,19
   15,11
Run Code Online (Sandbox Code Playgroud)

我已经读过SO中的先前帖子" 在数组中找到添加给定总和的数字对 "

为了找到有效的解决方案,需要多长时间?时间复杂度O(nlogn)还是O(n)?我试图通过分而治之的技术来做到这一点,但我没有得到退出条件的任何线索......

如果一个有效的解决方案包括使用两个指针对输入数组进行排序和操作元素,那么我认为我应该采用最少的O(nlogn)...

是否有任何数学相关的技术带来解决方案O(n).任何帮助表示赞赏..

c arrays algorithm performance

14
推荐指数
2
解决办法
4890
查看次数

算法的运行时间优化

我正试图找到一种方法来优化我的算法,使运行时间为O(n²)(Big O Notation).

输入是一个包含n个元素的数组,只有正整数和负整数.我们可以假设数组已经排序.

我必须确定:对于每个r(数组的元素),r = s + t,其中s和t也是数组的元素,并且可以是相同的(s == t),或者也是零.

我试图通过检查当前数字是正数还是负数来减少我必须检查的元素数量,但是运行时间仍然太长.问题是我使用了3个while循环,这意味着在最坏的情况下运行时间为O(n³).

这是我的代码:

public static void Checker(int[] array) {
    List<Integer> testlist = new ArrayList<Integer>();
    int i = 0;
    while (i < array.length) {
        int current = array[i];
        if (attached(current, array)) {
            testlist.add(current);
        }
        i++;
    }
}

public static boolean attached(int current, int[] array) {
    boolean result = false;
    int i = 0;
    while (i < array.length && !result) {
        int number1 = array[i];
        int j = 0;
        while (j < …
Run Code Online (Sandbox Code Playgroud)

algorithm optimization time big-o while-loop

7
推荐指数
1
解决办法
94
查看次数

确定数组是否包含两个等于某个总和的元素?

// Checks whether the array contains two elements whose sum is s.
// Input: A list of numbers and an integer s
// Output: return True if the answer is yes, else return False

public static boolean calvalue (int[] numbers, int s){
for (int i=0; i< numbers.length; i++){
    for (int j=i+1; j<numbers.length;j++){
        if (numbers[i] < s){
            if (numbers[i]+numbers[j] == s){
                return true;
                }
            }
        }
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

java algorithm performance

4
推荐指数
3
解决办法
2万
查看次数

标签 统计

algorithm ×4

performance ×2

arrays ×1

big-o ×1

c ×1

java ×1

optimization ×1

time ×1

while-loop ×1