algorithm - 这是否在 O(N log(N)) 时间内解决了 3SUM?

标签 algorithm time-complexity complexity-theory theory

此算法是否可以解决 O(N log(N)) 中的 3SUM 问题,维基百科将此问题定义为

In computational complexity theory, the 3SUM problem asks if a given set of n real numbers contains three elements that sum to zero.

//Given an array of integers called list
//return true if 3 integers in list sum to 0, false otherwise

//quicksort the provided list
quickSort(list)

//add all elements of the list to a hashmap where the key is a number and the value is the number of times it occurs
hs = new hashMap<Integer, Integer>()
for(Integer i:list)
   if(hs.get(i)==null)
        hs.add(i, 1)
    else
        hs.add(i, hs.get(i)+1)

//create a pair of pointers pointing to the left of right of the center of array
startIndex=0
while (list[startIndex]<0 and startIndex<list.length-1)
startIndex++

left=startIndex
right=startIndex+1

//run this loop while pointers are in boundaries of array
while(! (left<0 or right>=list.length)
{
    //see if a 3rd number that can be added to the numbers at left
    //and right to make 0 can be found
    sum=list[left] + list[right]
    negsum= -(sum)
    //if it's found enter these if statements
    if(hs.get(negsum)!=null)
    {
        //check for the possibility that the 3rd number is one of the 1st 2, if not return true 
       if(negsum==list[left] or negsum== list[right])
       {
        //if the 3rd number is one of the 1st 2 make sure that a duplicate of it exists, or if all 3 are 0, that 3 zeros exist
        //if we have enough duplicates, return true
            if(list[left]==list[right] )
                if(list.hasMoreThanTwo(negsum))
                    return true
            else if(list.hasMoreThanOne(negsum))
                return true
       }
       else
           return true
    }

    //if a trio cannot be formed with the numbers at left and right, adjust the pointers so that we will get closer to 0 and try again.
    if (sum<0)
        right++
    else
        left--
}

//if pointers go out of bounds 3 numbers that sum to 0 don't exist
return false

最佳答案

您的代码无法处理这种情况:

[-10, -7, 0, 0, 4, 6].

在这种情况下,右指针将越界,因为左指针将位于 -10,这太大了。

因此,如果某件事确实是负面的,您的算法将尝试寻找正面的解决方案,但最终会失败。

关于algorithm - 这是否在 O(N log(N)) 时间内解决了 3SUM?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46008675/

相关文章:

algorithm - 在部分排序的数组中,插入比归并排序有何优势?

Java:根据多个规则替换字符串

algorithm - 分解字符串以形成有效的表达式

c++ - 处理大型数据集 - 算法结果与 1k 条目测试匹配,但在 100 万条目测试中失败 - 相同的算法

runtime - 该伪代码的下限运行时

language-agnostic - O(N log N) 复杂度 - 类似于线性?

algorithm - 如何确定范围列表是否涵盖给定范围?

algorithm - 如果向无向加权图 G 添加了一条新边,则查找 MST T 是否仍然是新图 G' 的 MST

javascript - 如何减少 0(n) 以找到求和特定值的对的第一个实例

java - 大多数编程语言的时间复杂度?