记录4月上旬华为OD机试算法题

112 阅读1分钟

题目

1.输出字符串中所有数字之和

'bb12-34aa' => -31
'bb12-3-4aa' => -4

2.输出两个数组中满足差值小于某个阈值的组合(数组都是从小到大顺序排列)

m: [1, 5, 5, 10]
n: [1, 3, 8, 8, 20]
k: 5
输出 [[1, 1] [5, 8] [5, 8]]

3.涉及到动态规划,原谅我太菜

答案

Talk is cheap.Show me the code

    // 循环
    function sumNumbersInString(str) {
      let res = 0;
      for (let i = 0; i < str.length; i++) {
        const char = str[i];
        if (/[0-9]/.test(char)) {
          res += parseInt(char);
        }
        if (char === "-") {
          let num = "-",
            j = i + 1;

          while (/[0-9]/.test(str[j])) {
            num += str[j];
            j++;
          }
          i = j - 1;
          res += parseInt(num);
        }
      }
      console.log(res);
    }
    sumNumbersInString("bb12-3-4aa") // 5
    sumNumbersInString("bb12-34aa") // -31
   // 最开始用双循环加标志位,测试用例跑到10/20就不行了,个人感觉应该是时间复杂度O(n^2)超了
   // 后面下来ds搜下可以采用双指针
   function findUniqueThreshold(arr1, arr2, threshold) {
      const result = [];
      let i = 0,
        j = 0;

      while (i < arr1.length && j < arr2.length) {
        const a = arr1[i],
          b = arr2[j];

        if (b - a >= 0 && b - a <= threshold) {
          result.push([a, b]);
          i++;
          j++;
        } else if (b - a < 0) {
          j++;
        } else {
          i++;
        }
      }
      console.log(result);
    }
    findUniqueThreshold([1, 5, 5, 10], [1, 3, 8, 8, 20], 5);

总结

本次机试有点不顺,macOS牛客网客户端打开录屏后,键盘输入无反应,跟HR联系后只能重启,然后手机扫码进入小程序,我以为只要手机停留在小程序页面即可就平放了,结果谁知道这是拿来录像的,并且android手机操作系统没任何提示(水有点深),由于没有录像理所当然的挂了,继续前行吧!