JS刷题笔记(一)之基础题

1.

Given two arrays a and b write a function comp(a, b) (compSame(a, b) in Clojure) that checks whether the two arrays have the "same" elements, with the same multiplicities. "Same" means, here, that the elements in b are the elements in a squared, regardless of the order.

Examples

Valid arrays

a = [121, 144, 19, 161, 19, 144, 19, 11]  
b = [121, 14641, 20736, 361, 25921, 361, 20736, 361]

comp(a, b) returns true because in b 121 is the square of 11, 14641 is the square of 121, 20736 the square of 144, 361 the square of 19, 25921 the square of 161, and so on. It gets obvious if we write b's elements in terms of squares:

a = [121, 144, 19, 161, 19, 144, 19, 11] 
b = [11*11, 121*121, 144*144, 19*19, 161*161, 19*19, 144*144, 19*19]

Invalid arrays

If we change the first number to something else, comp may not return true anymore:

a = [121, 144, 19, 161, 19, 144, 19, 11]  
b = [132, 14641, 20736, 361, 25921, 361, 20736, 361]

comp(a,b) returns false because in b 132 is not the square of any number of a.

a = [121, 144, 19, 161, 19, 144, 19, 11]  
b = [121, 14641, 20736, 36100, 25921, 361, 20736, 361]

comp(a,b) returns false because in b 36100 is not the square of any number of a.

Remarks

a or b might be [] (all languages except R, Shell). a or b might be nil or null or None or nothing (except in Haskell, Elixir, C++, Rust, R, Shell, PureScript).

If a or b are nil (or null or None), the problem doesn't make sense so return false.

If a or b are empty then the result is self-evident.

a or b are empty or not empty lists.

分析:看懂题目意思很容易可以想到答案。一般会有两种分析思路:

(1)暴力:对array1中的数平方后与array2直接对比,时间复杂度O(n2)

(2)排序后对比,时间复杂度O(n)+O(lgn)

当然是第二种思路比较简单

这里要注意,记得判断数组是否为空

补充说明一下Array中map的使用方法:

map()方法定义在JavaScript的Array中,它返回一个新的数组,数组中的元素为原始数组调用函数处理后的值。map方法不会改变原始数组的值

array.map(function(currentValue, index, arr), thisIndex)

function是必选参数,Array中每一个值都会执行一边,形成一个新的数组。

代码如下:

function comp(array1, array2){
    //your code here
    if(array1==null || array2==null) return false;
    if(array1.length!=array2.length) return false;
    array1=array1.map((x)=>{
      return x*x;
    })
    array1.sort();
    array2.sort();
    for (var i=0;i<array1.length;i++)
    {
        if(array1[i]!=array2[i]) return false;
    }
    return true;
}

2.

Some numbers have funny properties. For example:

89 --> 8¹ + 9² = 89 * 1

695 --> 6² + 9³ + 5⁴= 1390 = 695 * 2

46288 --> 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51

Given a positive integer n written as abcd... (a, b, c, d... being digits) and a positive integer p

  • we want to find a positive integer k, if it exists, such as the sum of the digits of n taken to the successive powers of p is equal to k * n.

In other words:

Is there an integer k such as : (a ^ p + b ^ (p+1) + c ^(p+2) + d ^ (p+3) + ...) = n * k

If it is the case we will return k, if not return -1.

Note: n and p will always be given as strictly positive integers.

digPow(89, 1) should return 1 since 8¹ + 9² = 89 = 89 * 1
digPow(92, 1) should return -1 since there is no k such as 9¹ + 2² equals 92 * k
digPow(695, 2) should return 2 since 6² + 9³ + 5⁴= 1390 = 695 * 2
digPow(46288, 3) should return 51 since 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51

思路分析:题目意思比较好理解。解题分为

(1)取出数字中的所有单个数字

(2)求和计算

(3)判断是否存在k

易错点:

(1)在JS中,只有Number类型的数字,而Number类型中,整数/整数 是可以直接得到小数的,而不是像JAVA,C++那样直接

得到一个整数。

(2)求和计算是要求计算某个数的N次幂。

分享两种方法

(1)硬来

function digPow(n, p){
    // ...
    var n_t=n;
    array1= new Array(100);
    var num=0;
    var sum=0;
    while (n_t!=0){
        array1[num]=n_t%10;
        n_t=Math.floor(n_t/10);//舍去小数部分,把小数转换成整数
        num++;
    }
    for(var i=num-1;i>=0;i--)
    {
        var temp=1;
        for(var j=0;j<p;j++) temp=array1[i]*temp;
        sum+=temp;
        p++;
    }
    if(sum%n==0) return sum/n;
    else return -1;
}

(2)按位取整数的灵活思路,先将数字转换成字符,然后按位读取,最后再转换成整数

Math.pow(a,b) 计算a的b次方

String.charAt(i) 按下表取出字符串中单个字符

function digPow(n, p){
   var num1 = n.toString();
   var sum=0;
   for(var i=0;i<num1.length;i++)
   {
       sum+=Math.pow(parseInt(num1.charAt(i)),p)
       p++;
       if(sum%n==0) return sum/n;
   }
   return -1;
}

3.

The museum of incredible dull things

The museum of incredible dull things wants to get rid of some exhibitions. Miriam, the interior architect, comes up with a plan to remove the most boring exhibitions. She gives them a rating, and then removes the one with the lowest rating.

However, just as she finished rating all exhibitions, she's off to an important fair, so she asks you to write a program that tells her the ratings of the items after one removed the lowest one. Fair enough.

Task

Given an array of integers, remove the smallest value. Do not mutate the original array/list. If there are multiple elements with the same value, remove the one with a lower index. If you get an empty array/list, return an empty array/list.

Don't change the order of the elements that are left.

Examples

removeSmallest([1,2,3,4,5]) = [2,3,4,5]
removeSmallest([5,3,2,1,4]) = [5,3,2,4]
removeSmallest([2,2,1,2,1]) = [2,2,2,1]

看完题目:解题思路如下:
(1)找到最小值

(2)移除最小值

这里唯一要注意的是mutate,即不要对原始数组做任何改变,意思返回一个新的数组就行了呗,答案如下:

function removeSmallest(numbers) {
    if(numbers==null) return numbers;
    var temp= Math.min(...numbers);
    var newNums=[];
    var index = numbers.indexOf(temp);
    for (var i=0;i<numbers.length;i++)
    {
        if(i!=index) newNums.push(numbers[i]);
    }
    return newNums;
}

这里在说一个JS函数的用法

Math.max()是求最大值,Math.min()是求最小值

Math.max(value1,value2,value3....)//求最大值
Math.max(value1,value2,value3....)//求最小值

但是如果是数组或者对象呢?

var numArr = [1,2,4,6,76]

 Math.max(...numArr)//里面的参数真的有三个点,不用怀疑

4.

The main idea is to count all the occurring characters(UTF-8) in string. If you have string like this aba then the result should be { 'a': 2, 'b': 1 }

What if the string is empty ? Then the result should be empty object literal { }

思路:思路很简单,就是数字符。但这个题目的test数据不太好,只有a,b两种字符检验,可以让人钻空子。

钻孔子代码:

function count (string) {
    // The function code should be here
    if(string=="") return {};
    obj = new Object();
    for(var i=0;i<string.length;i++)
    {
        if(string[i]=='a'){
            if(obj.a==null) obj.a=1;
            else obj.a++;
        }
        else
        {
            if(obj.b==null) obj.b=1;
            else  obj.b++;
        }
    }
    return obj;
}

真正准确的代码

function count (string) {  
  var count = {};
  string.split('').forEach(function(s) {
     count[s] ? count[s]++ : count[s] = 1;
  });
  return count;
}

顺便讲解一下Array中的forEach方法

array.forEach(v=>{  
    console.log(v);  
});

array.forEach(function(v){  
    console.log(v);  
});

split方法只是把字符串分解为字符数组

var count={}等价于

var count= new Object();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值