Array of JS algorithm

Leetcode88: merge two ordered arrays

There are many methods. You can insert nums2 directly after nums1 and then sort, or you can use double pointers to directly insert the elements of nums2 into the appropriate position in nums1.

Double pointer:

//目的是将nums2的元素都插入到nums1中,所以循环判断以n为主
var merge = function(nums1, m, nums2, n) {
    
    
    let len = m + n -1;
    m--;n--;
    while(n>=0){
    
    
        nums1[len--] = nums1[m] > nums2[n] ? nums1[m--] : nums2[n--]
    }
};
//这里用到,如果nums1的数组先用完的话,那么nums[负数]会成为undefined,在做比较时会转换成NaN,任何比较都会返回false
// 这个主要是为了用一下splice和扩展符,所以步骤有点冗余。
var merge = function(nums1, m, nums2, n) {
    
    
    let len = m + n -1;
    m--;n--;
    while(m>=0 && n>=0){
    
    
        if(nums1[m] > nums2[n]){
    
    
            nums1[len--] = nums1[m--];
        }else{
    
    
            nums1[len--] = nums2[n--];
        }
    }
    if(n>=0){
    
    
        nums1.splice(0,n+1,...nums2.splice(0,n+1))
    }
    return nums1
};

leetcode349: the intersection of two arrays

SetObjects allow you to store any type of unique value, whether it is a primitive value or an object reference. SetAn object is a collection of values, and you can iterate its elements in the order of insertion. The elements in the Set will only appear once , that is, the elements in the Set are unique.

The Array.from() method creates a new, shallow-copy array instance from an array-like or iterable object

var intersection = function(nums1, nums2) {
    
    
    var newn =  nums1.filter((item) => {
    
    
        return nums2.indexOf(item)!=-1
    })
    return Array.from(new Set(newn))
};

Tencent: Array flattening, de-duplication, and sorting

Interview questions:

The following array is known: var arr = [[1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14]] ] ], 10];

Write a program to flatten the array and remove the repeated part of the data, and finally get an ascending and non-repeating array

Array flattening is to convert a multi-level nested array to only one level

let res = Array.from(new Set(arr.flat(Infinity))).sort((a,b) => a-b)

Flat:

  • Recursive implementation:

    • function flatten(arr){
              
              
          let res = [];
          for(let i = 0; i < arr.length; i++){
              
              
              if(Array.isArray(arr[i])){
              
              
                  res.push(...flatten(arr[i]));
              }else{
              
              
                  res.push(arr[i])
              }
          }
          return res;
      }
      
  • reduce achieve

    • function flatten(arr) {
              
              
        return arr.reduce((res,cur) => {
              
              
          return res.concat(Array.isArray(cur)? flatten(cur) : cur)
        },[])
      }
      
  • Use the ...spread operator ...to expand a level of nesting, such as: …[1,2,[3,4]] The result is [1,2,3,4], but …[1,[2,[3,4 ]]] The result is [1,2,[3,4]]

    • function(arr){
              
              
          while(arr.some(item => Array.isArray(item)){
              
              
          	arr = [].concat(...arr)      
          })
      }
      
  • ES6's flat(), arr.flat(depth): The parameter depth specifies the number of layers to be flattened, the default is 1, and the parameter can be set to Infinity until it is flattened to one layer.

    • var arr = arr.flat(Infinity)
      

leetcode15: the sum of three numbers (medium)

Realize O(n^2) with double pointer

var threeSum = function(nums) {
    
    
  nums.sort((a,b) => a-b);
  const res = [];
  for(let i=0; i<nums.length-2; i++){
    
    
      let n1 = nums[i];
      if(nums[i] > 0 ) break;
      if(i-1>=0 && nums[i] == nums[i-1]) continue;
      let l = i+1;
      let r = nums.length-1;
      while(l<r){
    
    
          let n2 = nums[l],n3 = nums[r];
          if(nums[i]+nums[l]+nums[r]==0){
    
    
              res.push([n1,n2,n3])
              while(l<r && nums[l]==n2) l++;
              while(l<r && nums[r]==n3) r--;
          }else if(nums[i]+nums[l]+nums[r] < 0){
    
    
              l++;
          }else{
    
    
              r--;
          }
      }
  }
  return res;
};

Guess you like

Origin blog.csdn.net/Pinoochio/article/details/113619403