LeetCode solution (using JavaScript) [3]

(1) Create the target array in a predetermined order

You are given two integer arrays nums and index. You need to create the target array according to the following rules:

The target array target is initially empty.
Read nums[i] and index[i] sequentially from left to right, and insert the value nums[i] at the subscript index[i] in the target array.
Repeat the previous step until there are no elements to read in either nums or index.
Please return the target array.

The title guarantees that the number insertion position always exists.

/**
 * @param {number[]} nums
 * @param {number[]} index
 * @return {number[]}
 */
var createTargetArray = function(nums, index) {
    
    
var a = [];
for(var i = 0;i<nums.length;i++){
    
    //对数组进行循环遍历
    a.splice(index[i],0,nums[i]);
	//向a数组中的index[]位置添加nums[i]这个数,删除0个数。
	}
return a;
};

Note:
The splice() method adds/removes items to/from the array and returns the removed item.

Note: This method mutates the original array. So what return a gets is the inserted a array, which is the new array we requested.
Syntax
arrayObject.splice(index,howmany,item1,...,itemX)

parameter describe
index required An integer specifying where to add/remove items, use a negative number to specify a position from the end of the array.
howmany required The number of items to delete. If set to 0, items will not be removed.
item1, …, itemX optional New items added to the array.

(2) Delete the node in the linked list

Please write a function that can delete a given (non-end) node in a linked list, you will only be given the node that needs to be deleted.

There is an existing linked list – head = [4,5,1,9], which can be expressed as:
4->5->1->9
Example 1:

Input: head = [4,5,1,9], node = 5
Output: [4,1,9]
Explanation: Given the second node in your linked list with value 5, after calling your function , the linked list should become 4 -> 1 -> 9.
Example 2:

Input: head = [4,5,1,9], node = 1
Output: [4,5,9]
Explanation: Given the third node in your linked list with value 1, then after calling your function , the linked list should become 4 -> 5 -> 9.

illustrate:

A linked list contains at least two nodes.
The values ​​of all nodes in the linked list are unique.
The given node is not the end node and must be a valid node in the linked list.
Don't return any results from your function.

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} node
 * @return {void} Do not return anything, modify node in-place instead.
 */
var deleteNode = function(node) {
    
    
    node.val=node.next.val;
    node.next=node.next.next;
};

Note:
In order to delete a node in the contact list, the next node is actually deleted.

For example, if [4,5,1,9] is to be deleted, if it is 5, first let node.val=node.next.val, then it becomes [4,1,1,9], and then proceed to node The operation of .next=node.next.next is equivalent to deleting the second 1, and the final result becomes [4,1,9].

(3) Minimum time to visit all points

There are n points on the plane, and the positions of the points are represented by integer coordinates points[i] = [xi, yi]. Please calculate the minimum time (in seconds) required to visit all these points.

You can move on the plane according to the following rules:

Move one unit length horizontally or vertically every second, or cross a diagonal line (can be regarded as moving one unit length horizontally and vertically in one second).
The points must be accessed in the order they appear in the array.

Example 1:
insert image description here Input: points = [[1,1],[3,4],[-1,0]]
Output: 7
Explanation: An optimal access path is: [1,1] -> [2, 2] -> [3,3] -> [3,4] -> [2,3] -> [1,2] -> [0,1] -> [-1,0]
from [1,1 ] to [3,4] takes 3 seconds
from [3,4] to [-1,0] takes 4 seconds
for a total of 7 seconds

Example 2:

Input: points = [[3,2],[-2,2]]
Output: 5

Source: LeetCode
Link: https://leetcode-cn.com/problems/minimum-time-visiting-all-points
The copyright belongs to LeetCode. For commercial reprints, please contact the official authorization, for non-commercial reprints, please indicate the source.

/**
 * @param {number[][]} points
 * @return {number}
 */
var minTimeToVisitAllPoints = function(points) {
    
    

var a = 0;
for(var i = 0;i<points.length-1;i++)
{
    
    
  var x =  Math.abs(points[i][0]-points[i+1][0]);
  var y =  Math.abs(points[i][1]-points[i+1][1]);
  if(x==y)
  {
    
    a = a+x;}
  else if(x>y)
  {
    
    a = a+x;}
  else 
  {
    
    a = a+y;
  }
}
return a;
};

Solution:
insert image description here
Because it is the Chebyshev distance, we only need to traverse all the adjacent points, and then calculate the sum of the Chebyshev distances.
To determine that the return value is a value, it needs to be defined. Then compare the absolute values ​​of the x-axis and y-axis in the loop, add the larger one to the return value, and finally traverse to get the final result.

(4) Convert binary linked list to integer

Give you a reference node head of a singly linked list. The value of each node in the linked list is either 0 or 1. This linked list is known to be a binary representation of an integer number.

Please return the decimal value of the number represented by the linked list.
Example 1:
1->0->1
Input: head = [1,0,1]
Output: 5
Explanation: Convert binary number (101) to decimal number (5)
Example 2:

Input: head = [0]
Output: 0
Example 3:

input: head = [1]
output: 1
example 4:

Input: head = [1,0,0,1,0,0,1,1,1,0,0,0,0,0,0]
Output: 18880
Example 5:

Input: head = [0,0]
Output: 0

hint:

The linked list is not empty.
The total number of nodes in the linked list does not exceed 30.
The value of each node is either 0 or 1.

Source: LeetCode
Link: https://leetcode-cn.com/problems/convert-binary-number-in-a-linked-list-to-integer
The copyright belongs to Leetcode Network. For commercial reprints, please contact the official authorization, for non-commercial reprints, please indicate the source.

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {number}
 */
var getDecimalValue = function(head) {
    
    
    //将链表转换成字符串
    number = '';
    while(head)
    {
    
    
        number += head.val;
        head = head.next;
    }
    return parseInt(number,2);
};

Solution:
First convert the linked list into a string, and then use the parseInt function to parse the string into an integer.
The explanation of the parseInt function in w3school
use and
uses the base mode (the author still has a little understanding of this function).
The following extends the type conversion in ECMAScript
insert image description here

(5) Take coins

There are n piles of Likou coins on the table, and the number of each pile is stored in the array coins. We can choose any pile each time, take one or two of them, and find the minimum number of times to get all the coins.

Example 1:

Input: [4,2,1]

Output: 4

Explanation: The first pile of Likou coins needs to be taken at least 2 times, the second pile needs to be taken at least 1 time, and the third pile needs to be taken at least 1 time. A total of 4 times can be taken.

Example 2:

Input: [2,3,10]

Output: 8

limit:

1 <= n <= 4
1 <= coins[i] <= 10

Source: LeetCode
Link: https://leetcode-cn.com/problems/na-ying-bi
Copyright belongs to LeetCode Network. For commercial reprints, please contact the official authorization, for non-commercial reprints, please indicate the source.

/**
 * @param {number[]} coins
 * @return {number}
 */
var minCount = function(coins) {
    
    
    var n = 0;
    for(i=0;i<coins.length;i++){
    
    
        if(coins[i]%2==0)
        {
    
    
            n +=coins[i]/2; 
        }
        else
        {
    
    
            n +=Math.floor(coins[i]/2)+1; 
        }
    }
    return n;
};

Solution
This time, Math.floor is used again.
insert image description here
The numbers in the
solution array need to be traversed in turn, and what we return is a number, which is the sum of the number of operations for each value in the array. When operating on the numbers in the array, we need to discuss the odd and even numbers. , in js, if a is an odd number, a/2 does not necessarily get an adjacent integer, so you need to use the Math.floor function to get the value.
(The reason why I made a mistake at the beginning of this question is that the Math.floor function was not used, but the division operation was performed directly) i

Postscript: I have done a lot of questions in a few days, and I gradually like this feeling, but I still have a relatively blind spot for some knowledge. Even if I see other people's solutions, I still feel that it is very difficult to do, and it is still a problem of knowledge reserve.

Guess you like

Origin blog.csdn.net/weixin_34727238/article/details/106073561