9.19同花顺笔试
题目太多了 简单记录下其中几道手写题好了。
- 输入出生日期,返回距离还有多少天生日
function happyBirthday(year,mon,day){ let now = new Date() let last = new Date(year,mon,day) let nextBirth = new Date(now.getFullYear(),last.getMonth(),last.getDate()) return new Date(nextBirth-now).getDate() }
- 输入一个数组[1,5,2,4,6,3] 让里面的数两两配对,取队里的小值,返回总和最小
输入:[1,5,2,4,6,3] 输出:6 [1,6] [2,4] [3,5] 1+2+3
这个排序后res加前一个,然后指针往下走就行了function MysortSum(nums){ nums.sort() let res = 0 while(nums.length){ res+=nums[0] nums.pop() nums.shift() } return res }
- 生存主题,现有N瓶水,D元钱,每天需要消耗X元Y瓶水 购物的话 每瓶水需要P元 求最多生存多少天
思路:先把手头的水喝完,先考虑水再考虑钱。有点贪心var stillAlive = function(N,D,X,Y,P){ // N水 D元 // 消耗 X元 Y水 // 一瓶水 P元 // 先考虑把手上的水喝完 let nowWater = N let nowMoney = D let LostWater = Y let LostMoney = X let buyWater = P let res = 0 while(true){ nowMoney -= LostMoney nowWater -= LostWater if(nowWater<0){ // 不够喝水了 花钱 nowMoney -= buyWater*(Math.abs(nowWater)) nowWater = 0 } if(nowMoney>0){ // 这天撑过去了 res++ }else{ // 这天没撑过去 return res } } }
- 给一个数组,把0放置到数组后面***** 要求语言python/c/java
想了想还是用最熟悉的js好了,不调用库函数方法的话其实没多大差
思路:双指针遍历 一个头开始 一个尾巴开始 尾巴开始的遇到非零暂停,头开始的遇到零暂停,然后两个指针交换。var pushZero = function(nums){ let pre = 0 let end = nums.length-1 while(nums[end]==0){ end-- } while(pre<end){ if(nums[pre]!=0){ pre++ continue }else{ // 交换pre跟end let temp = nums[pre] nums[pre] = nums[end] nums[end] = temp end-- while(nums[end]==0){ end-- } } } return nums }
- 函数柯里化
let currying = funciton(fn){ let curry = function(...args){ if(args.length>fn.length){ return fn.apply(this,[...args]) }else{ return function hi(...args2){ return curry.apply(this,[...args].concat([...args2])) } } } return curry } function add1(x,y){ return x+y }