首页 技术 正文
技术 2022年11月14日
0 收藏 994 点赞 2,171 浏览 1753 个字

在此记录一下用javascript刷leetcode的过程,每天都要坚持!

1.Two Sum

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.

Please note that your returned answers (both index1 and index2) are not zero-based.You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9Output: index1=1, index2=2

/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
var len = nums.length,
need,
map = {},
numbers = [];
for(var i = 0; i < len; i++){
need = target - nums[i];
if(need in map){
numbers.push(map[need] + 1);
numbers.push(i + 1);
break;
}else{
map[nums[i]] = i;
}
}
return numbers;
};

这道题目注意下复杂度别傻傻的用双循环…

20.Valid Parentheses

Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[‘ and ‘]’, determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

/**
* @param {string} s
* @return {boolean}
*/
var isValid = function(s) {
var len = s.length,
cur,
stack = [],
map = {'(':')','[':']','{':'}'};
for(var i = 0; i < len; i++) {
cur = s[i];
if(map.hasOwnProperty(cur)){
stack.push(cur);
}else{
if(stack.length === 0){
return false;
}else{
stackTop = stack.pop();
if(map[stackTop] !== cur){
return false;
}
}
}
}
if(stack.length === 0){
return true;
}else{
return false;
}};

这道题目是利用堆栈的,比较巧妙,数据结构很多记不得了,最近抽时间多翻翻。

189.Rotate Array

Rotate an array of n elements to the right by k steps.

For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].

/**
* @param {number[]} nums
* @param {number} k
* @return {void} Do not return anything, modify nums in-place instead.
*/
var rotate = function(nums, k) {
var len = nums.length;
if(len === 0 || len === 1 || k===0){
return;
}
var move = nums.splice(len - k,len);
for(var i = move.length - 1;i >= 0;i--){
nums.unshift(move[i]);
}
};

这题用js写的话就是考察下数组操作方法了,注意下特殊情况即可。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,083
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,558
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,407
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,180
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,816
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,899