Sword offer-time efficiency

1. The number of occurrences in the array exceeds half

Problem Description:

There is a number in the array that appears more than half the length of the array. Please find this number. For example, enter an array of length [1,2,3,2,2,2,5,4,2]. Since the number 2 appears in the array 5 times, more than half the length of the array, so output 2. If it does not exist, output 0.

function MoreThanHalfNum_Solution(numbers) {
  // write code here
  var len = numbers.length;
  var obj = {};
  numbers.forEach((item) => {
    if (!obj[item]) {
      obj[item] = 1;
    } else {
      obj[item]++;
    }
  });
  for (let key in obj) {
    if (obj[key] > len / 2) {
      return key;
    }
  }
  return 0;
}

2. The smallest number of K

Problem Description:

Enter n integers to find the smallest K number. For example, enter 4, 5, 1, 6, 2, 7, 3, and 8 digits, then the smallest 4 digits are 1, 2, 3, and 4.

Method One: Quick Sort

function GetLeastNumbers_Solution(input, k) {
  // write code here
  if (k > input.length) return [];
  quickSort(input);
  return input.slice(0, k);
}

function quickSort(input, left = 0, right = input.length - 1) {
  if (left >= right) return;
  var baseId = left;
  var baseVal = input[baseId];
  var i = left;
  var j = right;
  while (i < j) {
    while (j > i && input[j] >= baseVal) {
      j--;
    }
    while (i < j && input[i] <= baseVal) {
      i++;
    }
    [input[i], input[j]] = [input[j], input[i]];
  }
  [input[baseId], input[j]] = [input[j], input[baseId]];
  quickSort(input, left, j - 1);
  quickSort(input, j + 1, right);
  return input;
}

Method 2: Bubble sort

function GetLeastNumbers_Solution(input, k) {
  // write code here
  if (k > input.length) return [];
  for (let j = input.length - 1; j >= input.length - k; j--) {
    for (let i = 0; i < j; i++) {
      if (input[i] < input[i + 1]) {
        [input[i], input[i + 1]] = [input[i + 1], input[i]];
      }
    }
  }
  var res = [];
  while (k > 0) {
    res.push(input.pop());
    k--;
  }
  return res;
}

Method 3: sort

function GetLeastNumbers_Solution(input, k) {
  // write code here
  if (input.length < k) {
    return [];
  }
  input.sort((a, b) => a - b);
  return input.slice(0, k);
}

3. Maximum sum of consecutive subarrays

Problem Description:

HZ occasionally takes some professional questions to fool non-computer majors. After the test group meeting today, he spoke again: In ancient one-dimensional pattern recognition, it is often necessary to calculate the maximum sum of continuous subvectors. When the vectors are all positive numbers, the problem is solved well. However, if the vector contains negative numbers, should it contain a negative number and expect the positive number next to it to make up for it? For example: {6, -3, -2,7, -15,1,2,2}, the maximum sum of consecutive subvectors is 8 (starting from the 0th to the 3rd). Give an array and return the sum of its largest consecutive subsequences, will you be fooled by him? (The length of the subvector is at least 1)

/*
举例:array = [1, -2, 3, 10, -4, 7, 2, -5]
初始化 max = 1, temp = 1
i = 1时, temp = -1, max = 1
i = 2时, temp = 3,  max = 3
i = 3时, temp = 13, max = 13
i = 4时, temp = 9 , max = 13
i = 5时, temp = 16, max = 16
i = 6时, temp = 18, max = 18
i = 7时, temp = 13, max = 18;
*/

function FindGreatestSumOfSubArray(array) {
  // write code here
  var max = array[0],
    sum = array[0];
  for (let i = 1; i < array.length; i++) {
    if (sum <= 0) {
      sum = array[i]; //sum是负数说明前面的数没有贡献,重新赋值一个数
    } else {
      sum += array[i]; //sum不是负数说明当前值有贡献
    }
    if (sum > max) {
      max = sum;
    }
  }
  return max;
}

4. The number of occurrences of 1 in integers (the number of occurrences of 1 in integers from 1 to n)

Title description:

Find the number of occurrences of 1 in integers from 1 to 13 and calculate the number of occurrences of 1 in integers from 100 to 1300? For this reason, he counted the numbers in 1 ~ 13 that contain 1 as 1, 10, 11, 12, and 13 so they appeared 6 times in total, but he was not wrong about the latter problem. ACMer hopes you can help him and make the problem more general. You can quickly find the number of occurrences of 1 in any non-negative integer interval (the number of occurrences of 1 from 1 to n).

Method 1: For each digit, find the place by taking the remainder of 10 (% 10), then divide the original number by 10 to round, and then take the remainder of 10 to get ten ... and so on

function NumberOf1Between1AndN_Solution(n) {
  // write code here
  var count = 0;
  for (let i = n; i > 0; i--) {
    for (let j = i; j > 0; j = parseInt(j / 10)) {
      //对j/10取整
      if (j % 10 === 1) {
        count++;
      }
    }
  }
  return count;
}

Method two: stupid method, convert 1 to n into a string and stitch together to calculate the number of 1

function NumberOf1Between1AndN_Solution(n) {
  // write code here
  var str = "";
  for (let i = 0; i <= n; i++) {
    str += i;
  }
  var res = str.split("").filter((ele) => ele === "1");
  return res.length;
}

5. Arrange the integers to the smallest number

Problem Description:

Enter an array of positive integers, concatenate all the numbers in the array to form a number, and print the smallest of all the numbers that can be concatenated. For example, if you input the array {3, 32, 321}, the smallest number that can be arranged by these three numbers is 321323.

Problem-solving ideas:

Connect the numbers in the array to form the smallest number. Put 'large number' back and 'decimal' forward, how to define 'large number' and 'decimal'? For example, there are two numbers a and b. If ab> ba, then a is a 'large number' and b is a 'decimal number', which should be arranged as ba.

As a result, this question becomes a sorting problem, and the numbers that can make up the combined numbers will be moved back. Here we need to define a comparison method of the ratio. Bubble sorting can solve this problem.

function PrintMinNumber(numbers) {
  // write code here
  numbers.sort((a, b) => {
    return "" + a + b > "" + b + a ? 1 : -1; // ab 和 ba ASCII码值大的排在后面
    // return [a,b].join("")-[b,a].join("");
  });
  return numbers.join("");
}

Guess you like

Origin www.cnblogs.com/muzidaitou/p/12722094.html