改变常量值的排序方法

问题描述 投票:0回答:1

所以,我正在尝试这个LeetCode问题= https://leetcode.com/problems/two-sum/

我编写的解决方案要求我对数组进行排序,但是我需要返回与原始数组相关的索引。因此,我创建了一个常量来存储原始内容,然后在找到这些索引之后对其进行搜索。

我的解决方案最终无法正常工作,因为排序方法正在更改该常数值。我不知道为什么会这样,我只知道sort方法在调用时会改变原始数组(这就是为什么我需要在排序之前存储它)。我认为,如果创建了一个常量,则以后将无法更改。这就是为什么我认为这是错误或其他原因

这是我一直在尝试的代码(为了清楚起见,我将console.logs留在了那里)

要测试您应该使用

nums = [3, 2, 4]
target = 6
var twoSum = function(nums, target) {
    var max = nums.length - 1;
    var min = 0;

    const nums2 = nums;
    console.log(nums2)
    var nums1 = nums.sort(function(a,b){return a - b});
    console.log(nums2)
    while (min != max){

        if (nums1[min] + nums1[max] > target) {
            max -= 1;
        } else if (nums1[min] + nums1[max] < target) {
            min += 1;
        };        
        if (nums1[min] + nums1[max] == target) {
            return [nums2.indexOf(nums1[min]), nums2.indexOf(nums1[max])];        
        };
    };    
};
javascript arrays debugging
1个回答
0
投票

这里两件事:

  1. const nums2 = nums;执行not复制数组,它只是为您提供了一个不可重新分配的引用(例如,您无法使用nums2将新值分配给=,但是num2的内容已更新)抢夺]
  2. nums.sort(...)in place进行排序,因此它确实修改了原始数组(请参阅Array.prototype.sort)。由于nums2是对nums的引用,因此在第二个nums]中显示了对console.log的更改。
nums = [3, 2, 4]
target = 6
var twoSum = function(nums, target) {
    var max = nums.length - 1;
    var min = 0;

    // force a copy of the array
    // note: this is a shallow copy
    const nums2 = nums.slice();
    console.log(nums2)
    var nums1 = nums.sort(function(a,b){return a - b});
    console.log(nums2)
    while (min != max){

        if (nums1[min] + nums1[max] > target) {
            max -= 1;
        } else if (nums1[min] + nums1[max] < target) {
            min += 1;
        };        
        if (nums1[min] + nums1[max] == target) {
            return [nums2.indexOf(nums1[min]), nums2.indexOf(nums1[max])];        
        };
    };    
};

twoSum(nums, target);
© www.soinside.com 2019 - 2024. All rights reserved.