最接近的三数之和
var threeSumClosest = function ( nums, target ) {
const bijiao = ( a, b ) => {
return Math. abs ( target - a) > Math. abs ( target - b) ? b : a;
} ;
const nums2 = nums. sort ( ( a, b ) => a - b) ;
let sum = nums2[ 0 ] + nums2[ 1 ] + nums2[ 2 ] ;
const len = nums2. length;
for ( let i = 0 ; i < len; i++ ) {
let left = i + 1 ;
let right = len - 1 ;
while ( left < right) {
const he = nums2[ i] + nums2[ left] + nums2[ right] ;
if ( he > target) {
right-- ;
} else {
left++ ;
}
sum = bijiao ( sum, he) ;
}
}
return sum;
} ;
电话号码的字母组合
var letterCombinations = function ( digits ) {
if ( digits == "" ) return [ ] ;
const list = [
{ key : "2" , value : [ "a" , "b" , "c" ] } ,
{ key : "3" , value : [ "d" , "e" , "f" ] } ,
{ key : "4" , value : [ "g" , "h" , "i" ] } ,
{ key : "5" , value : [ "j" , "k" , "l" ] } ,
{ key : "6" , value : [ "m" , "n" , "o" ] } ,
{ key : "7" , value : [ "p" , "q" , "r" , "s" ] } ,
{ key : "8" , value : [ "t" , "u" , "v" ] } ,
{ key : "9" , value : [ "w" , "x" , "y" , "z" ] } ,
] ;
const len = digits. length;
const getlist = ( i, arr ) => {
if ( i > len - 1 ) return arr;
const listdata = list. find ( ( f ) => f. key == digits[ i] ) ;
let arr2 = [ ] ;
listdata. value. forEach ( ( e1 ) => {
arr. forEach ( ( e2 ) => {
arr2. push ( e2 + e1) ;
} ) ;
} ) ;
return getlist ( i + 1 , arr2) ;
} ;
return getlist ( 0 , [ "" ] ) ;
} ;
四数之和
var fourSum = function ( nums, target ) {
const nums1 = [ ] ;
for ( let n1 = 0 ; n1 < nums. length; n1++ ) {
const cishu = nums1. filter ( ( f ) => f == nums[ n1] ) . length;
if ( cishu < 4 ) {
nums1. push ( nums[ n1] ) ;
}
}
const nums2 = nums1. sort ( ( a, b ) => a - b) ;
const len = nums2. length;
let arr = [ ] ;
for ( let i1 = 0 ; i1 < len; i1++ ) {
if ( target > 0 && nums2[ i1] > target) break ;
for ( let i2 = i1 + 1 ; i2 < len; i2++ ) {
if ( target > 0 && nums2[ i1] + nums2[ i2] > target) break ;
for ( let i3 = i2 + 1 ; i3 < len; i3++ ) {
if ( target > 0 && nums2[ i1] + nums2[ i2] + nums2[ i3] > target) break ;
for ( let i4 = i3 + 1 ; i4 < len; i4++ ) {
if (
target > 0 &&
nums2[ i1] + nums2[ i2] + nums2[ i3] + nums2[ i4] > target
)
break ;
if ( nums2[ i1] + nums2[ i2] + nums2[ i3] + nums2[ i4] == target) {
arr. push ( ` ${ nums2[ i1] } , ${ nums2[ i2] } , ${ nums2[ i3] } , ${ nums2[ i4] } ` ) ;
}
}
}
}
}
const arr2 = Array. from ( new Set ( arr) ) ;
return arr2. map ( ( e ) => e. split ( "," ) . map ( ( m ) => Number ( m) ) ) ;
} ;
有效的括号
var isValid = function ( s ) {
const isLeft = ( s ) => {
return s == "[" || s == "{" || s == "(" ;
} ;
const left = {
"[" : 1 ,
"{" : 2 ,
"(" : 3 ,
} ;
const right = {
"]" : 1 ,
"}" : 2 ,
")" : 3 ,
} ;
const guize = [ ] ;
for ( let i = 0 ; i < s. length; i++ ) {
if ( isLeft ( s[ i] ) ) {
guize. push ( left[ s[ i] ] ) ;
} else {
if ( ! guize. length) return false ;
if ( right[ s[ i] ] != guize. at ( - 1 ) ) return false ;
else guize. pop ( ) ;
}
}
return ! guize. length;
} ;