[英]What is the time/space complexity of ES6 array swap?
So you can swap array elements using ES6 with the following notation: 因此,您可以使用以下表示法使用ES6交换数组元素:
let a = [1, 2, 3, 4];
[a[0], a[1]] = [a[1], a[0]];
console.log(a); // [2, 1, 3, 4];
But I'm curious to know the time/space complexity of this. 但我很想知道这个时间/空间的复杂性。
If it's just syntactic sugar for: 如果它只是语法糖:
var temp = a[0];
a[0] = a[1];
a[1] = temp;
Then I'd imagine it's O(1) for both time and space. 然后我想象时间和空间都是O(1)。
I suppose even if we are creating a whole new array to make the destructuring and then assignment, would still all be constant since we're only ever swapping a couple of elements. 我想即使我们正在创建一个全新的数组来进行解构,然后分配,仍然会保持不变,因为我们只交换了几个元素。 Does this sound right? 这听起来不错吗?
It's probably more like: 它可能更像是:
var temp1 = a[1];
var temp2 = a[0];
a[0] = temp1;
a[1] = temp2;
Although temp1
isn't really needed when just swapping two values, I wouldn't expect the compiler to be able to figure out which temporaries are needed and which aren't in more general cases. 虽然在交换两个值时并不真正需要temp1
,但我不希望编译器能够确定需要哪些临时值以及哪些不是更常见的情况。
But either way, it's O(n)
, where n
is the number of elements you're swapping. 但不管怎样,它都是O(n)
,其中n
是你交换的元素数量。 Any intermediate temporaries are just a constant factor, they don't affect the time complexity. 任何中间临时都只是一个常数因素,它们不会影响时间复杂度。
I suppose it does affect space complexity -- if the compiler could detect that only one temporary is needed, it would be O(1)
space. 我认为它确实会影响空间复杂性 - 如果编译器可以检测到只需要一个临时值,那么它将是O(1)
空间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.