Time complexity 时空复杂度法
我有一个问题要回答,要尽可能复杂 我们得到了一个排序数组(int)和X值。我们需要做的就是找出数组中有多少个位置等于X值 这是我对这种情况的解决方案,因为我对复杂性知之甚少。 我所知道的是,更好的方法没有for循环:XTime complexity 时空复杂度法,time-complexity,space-complexity,Time Complexity,Space Complexity,我有一个问题要回答,要尽可能复杂 我们得到了一个排序数组(int)和X值。我们需要做的就是找出数组中有多少个位置等于X值 这是我对这种情况的解决方案,因为我对复杂性知之甚少。 我所知道的是,更好的方法没有for循环:X class Question { public static int mount (int [] a, int x) { int first=0, last=a.length-1, count=0, pointer=0; boole
class Question
{
public static int mount (int [] a, int x)
{
int first=0, last=a.length-1, count=0, pointer=0;
boolean found=false, finish=false;
if (x < a[0] || x > a[a.length-1])
return 0;
while (! found) **//Searching any place in the array that equals to x value;**
{
if ( a[(first+last)/2] > x)
last = (first+last)/2;
else if ( a[(first+last)/2] < x)
first = (first+last)/2;
else
{
pointer = (first+last)/2;
count = 1;
found = true; break;
}
if (Math.abs(last-first) == 1)
{
if (a[first] == x)
{
pointer = first;
count = 1;
found = true;
}
else if (a[last] == x)
{
pointer = last;
count = 1;
found = true;
}
else
return 0;
}
if (first == last)
{
if (a[first] == x)
{
pointer = first;
count = 1;
found = true;
}
else
return 0;
}
}
int backPointer=pointer, forwardPointer=pointer;
boolean stop1=false, stop2= false;
while (!finish) **//Counting the number of places the X value is near our pointer.**
{
if (backPointer-1 >= 0)
if (a[backPointer-1] == x)
{
count++;
backPointer--;
}
else
stop1 = true;
if (forwardPointer+1 <= a.length-1)
if (a[forwardPointer+1] == x)
{
count++;
forwardPointer++;
}
else
stop2 = true;
if (stop1 && stop2)
finish=true;
}
return count;
}
public static void main (String [] args)
{
int [] a = {-25,0,5,11,11,99};
System.out.println(mount(a, 11));
}
}
你对变化有什么看法?我认为它会将时间复杂度更改为O(long(n))。首先让我们检查一下您的代码: 代码可以进行大量重构和清理(这也会导致更高效的实现,但不会提高时间或空间复杂性),但算法本身相当不错 它所做的是使用标准的二进制搜索来查找具有所需值的项,然后扫描到后面和前面以查找该值的所有其他匹配项 就时间复杂度而言,该算法是O(N)。最坏的情况是,整个数组都是相同的值,并且在第二阶段迭代所有数组(二进制搜索只需要1次迭代)。空间复杂度为O(1)。内存使用(空间)不受输入大小增长的影响 如果继续在2个子数组(前后)上使用二进制搜索并以对数方式增加“匹配范围”,则可以提高最坏情况下的时间复杂度。时间复杂度将变为O(log(N))。空间复杂性将保持O(1),原因与之前相同
但是,实际场景(数组包含各种值)的平均复杂度非常接近,甚至可能倾向于您自己的版本。Hi!我用新的while循环编辑了这篇文章,在第一个代码中修改了我的第二个while循环。你怎么认为?时间/空间复杂性是什么?再次感谢你,伙计@joock3r-如果你甚至懒得接受答案,不要指望别人会帮你对不起,我没有看到我没有按“答案”按钮。
while (!stop1 || !stop2) //Counting the number of places the X value is near our pointer.
{
if (!stop1)
{
if ( a[last] == x )
{
stop1 = true;
count += (last-pointer);
}
else if ( a[(last+forwardPointer)/2] == x )
{
if (last-forwardPointer == 1)
{
stop1 = true;
count += (forwardPointer-pointer);
}
else
forwardPointer = (last + forwardPointer) / 2;
}
else
last = ((last + forwardPointer) / 2) - 1;
}
if (!stop2)
{
if (a[first] == x)
{
stop2 = true;
count += (pointer - first);
}
else if ( a[(first+backPointer)/2] == x )
{
if (backPointer - first == 1)
{
stop2 = true;
count += (pointer-backPointer);
}
else
backPointer = (first + backPointer) / 2;
}
else
first = ((first + backPointer) / 2) + 1;
}
}