Only one number appears
Given an array of integers, nums, each element appears exactly three times except for one element. Find and return the element that appears only once.Copy the code
Input: nums = [2,2,3,2] output: 3 input: nums = [0,1,0,1,0,1,100] output: 100Copy the code
var singleNumber = function (nums) {
let set = new Set(nums);
let obj = {};
for(let value of nums) {
if(! obj[value]) { obj[value] =true;
} else {
set.delete(value)
}
}
return set.values().next().value
}
console.log(singleNumber([0.1.0.1.0.1.100]))
Copy the code
Delete at most one character to get palindrome
Given a non-empty string s, determine if you can get a palindrome string by removing at most one character from the string.Copy the code
Input: s = "ABA" Output: true Input: s = "ABCA" Output: true Description: The "C" or "B" characters can be deleted input: s = "ABC" Output: falseCopy the code
var validPalindrome = function(s) {
if(s.length <3) return true;
/ / double pointer
var left = 0;
var right = s.length -1;
var flag = 2;
var target = []; //2: jump left; 1: right jump; 0 no chance
while(left < right) {
if(s[left]! =s[right]) {switch(flag) {
case 2:
target = [left,right];
flag = 1;
left ++;
break
case 1:
left = target[0];
right = target[1] - 1;
flag = 0;
break
case 0:
return false; }}else {
left ++
right --
}
}
return true
}
Copy the code
Integer inversion
You are given a 32-bit signed integer x that returns the result of reversing the numeric portion of x. If the inverted integer exceeds the range of 32-bit signed integers [−231, 231 − 1], 0 is returned. Assume that the environment does not allow storage of 64-bit integers (signed or unsigned).Copy the code
Input: x = 123 Output: 321 Input: x = -123 Output: -321 Input: x = 120 Output: 21 Input: x = 0 Output: 0Copy the code
var reverse = function(x) {
const maxNumber = Math.pow(2.31) - 1;
const minNumber = Math.pow(-2.31);
const flag = x > 0 ?true : false;
// All positive numbers for comparison
x = flag ? x : -x;
x = +(x.toString().split(' ').reverse().join(' '));
x = flag ? x :-x;
// Compares whether the number after the inversion overflows
if(x > maxNumber || x < minNumber) return 0;
return x
};
let x = 120;
let result = reverse(x);
console.log(result)
Copy the code
Integer division
Given two integers A and b, the quotient of their division a/b requires that the multiplication sign '*', the division sign '/', and the remainder sign '%' should be truncated. For example: Truncate (8.345) = 8 and TRUNCate (-2.7335) = -2 Assume that our environment can store only 32-bit signed integers in the range of [−231, 231−1]. In this case, 231 − 1 is returned if the division result overflowsCopy the code
Input: A = 15, b = 2 Output: 7 Explanation: 15/2 = TRUNCate (7.5) = 7 Input: A = 7, B = -3 Output: -2 Explanation: 7/-3 = TRUNCate (-2.33333..) Input: a = 0, b = 1 Output: 0 Input: A = 1, b = 1 Output: 1Copy the code
var divide = function (a,b) {
if(a === -Math.pow(2.31) && b === -1) {
return Math.pow(2.31) -1;
}
let negative = a < 0 && b > 0 || a > 0 && b < 0;
a = a < 0 ? -a:a; // |a|
b = b < 0 ? -b:b; // |b|
let result = 0 ;
while(a >= b ) {
a = a-b;
result ++
}
return negative ? -result :result;
}
Copy the code
Looking for different
Given two strings s and t, they contain only lowercase letters. The string t is randomly rearranged by the string S, and a letter is added at the random position. Please find the letter added to t.Copy the code
Input: s = "abcd", t = "abcde" Output: "e" Explanation: 'e' is the letter being added. Input: s = "", t =" y "output:" y "type: s =" a ", t = "aa" output: "a" type: s = "ae", t = "aea" output: "a"Copy the code
var findTheDifference = function (s,t) {
// Change the original data
for(let item of s) {
t = t.replace(item,' ')}return t
}
Copy the code
The sum of three number
Given an array nums containing n integers, determine if there are three elements a, B, and c in nums such that a + b + c = 0. Please find all the triples that sum to 0 and are not repeated. > Note: The answer must not contain duplicate triples. Input: nums = [1, 2, 1, 4] output: [[1, 1, 2], [1, 1]] input: nums = [] output: [] input: nums = [0] output: []Copy the code
var threeSum = function(nums) {
let ans = [];
const len = nums.length;
if(nums == null || len < 3) return ans;
nums.sort((a,b) = > a-b); / / sorting
for(let i = 0; i < len ; i++) {
if(nums[i] > 0) break; // If the current number is greater than 0, the sum of the three numbers must be greater than 0, so end the loop
if( i > 0 && nums[i] == nums[i-1]) continue;/ / to heavy
let L = i+1;
let R = len-1;
while(L < R) {
const sum = nums[i] + nums[L] + nums[R];
if(sum == 0) {
ans.push([nums[i],nums[L],nums[R]]);
while(L<R && nums[L] == nums[L + 1]) L++;
while(L<R && nums[R] == nums[R - 1]) R--;
L ++;
R --;
}
else if (sum < 0) L++;
else if (sum > 0) R--; }}return ans;
}
Copy the code
The shortest string containing all characters
Given two strings s and t. Returns the shortest substring of all characters in s that contain t. An empty string "" is returned if no substring exists in s. If there are multiple substrings in s, return any one of them. Note: For repeated characters in t, we must look for substrings that have at least the number of characters in t.Copy the code
Input: s = "ADOBECODEBANC", t = "ABC" Output: "BANC" Explanation: The shortest substring "BANC" contains all the characters 'A', 'B', 'C' of the string T input: s = "A ", t = "A "Output: "A" Input: S = "a", t = "aa" Output: "" Explanation: both characters 'a' in t should be contained in a substring of S, so there is no eligible substring, return empty string.Copy the code
/ * * *@param {string} s
* @param {string} t
* @return {string}* /
var minWindow = function(s, t) {
const m = s.length, n = t.length;
// Create a need array to represent the number of characters in t, stored in ASCII
// Add need[76] = 2 to indicate that the ASCII 76 character needs two characters in the target string t. A negative number indicates that the current string is redundant in the window and needs to be filtered out
let need = new Array(128).fill(0);
// Add elements to need as per the contents of string t
for(let i = 0; i < n; i++){
need[t[i].charCodeAt()]++;
}
/* l: left edge of the slide window r: right edge of the slide window size: length of the slide window count: Length of the slide window start: If it is valid to update the sliding window, record the starting position of the window so that you can use */ to find substrings later
let l = 0, r = 0, size = Infinity, count = t.length, start = 0;
// The loop condition does not exceed the length of s
while(r < m){
// indicates that t contains the c character that is currently iterated through. Update the current size of count, which should be reduced by one
if(need[s[r].charCodeAt()] > 0){
count--;
}
// The count for that character in the need[] array is reduced by 1, regardless of whether the character is included in t
need[s[r].charCodeAt()]--;
//count==0 indicates that the current window contains all characters required by t
if(count === 0) {// If the value of the left boundary is less than 0 in the need[] array, it is a redundant element that is not included in t
while(l < r && need[s[l].charCodeAt()] < 0) {// Maintain and update this value in the need[] array, increment by 1
need[s[l].charCodeAt()]++;
// Move the left edge to the right to filter out the element
l++;
}
// If the current window value is smaller than the previously maintained window value, it needs to be updated
if(r - l + 1 < size){
// Update window values
size = r - l + 1;
// Update the starting position of the window so that it can be found later to return the result
start = l;
}
// increment the character count of position l by 1
need[s[l].charCodeAt()]++;
// Re-maintain the left boundary value and the currently required character value count
l++;
count++;
}
// Move the boundary right to start the next loop
r++;
}
return size == Infinity ? "" : s.substring(start,start + size);
};
Copy the code
Determines whether the parenthesis string is valid
Given a only include a '(',') ', '{','} ', '/', ' 'the string s, determine whether a string is effective. A valid string must meet the following requirements: The left parenthesis must be closed with the same type of the right parenthesis. The left parentheses must be closed in the correct order.Copy the code
Example 1: Input: s = "()" Output: true Example 2: Input: s = "()[]{}" Output: true Example 3: Input: s = "(]" Output: falseCopy the code
const isValid = function(s) {
if(s.length % 2= = =1) {
// If the length of s is odd then it is not closed
return false;
}
const regObj = {
"{":"}"."(":")"."[":"]"};let stack = [];
for(let i = 0; i < s.length; i++) {if(s[i] === "{" || s[i] === "[" || s[i] === "(") {
stack.push(s[i]);
} else {
const cur = stack.pop();
if(s[i] ! == regObj[cur]) {return false; }}}if(stack.length) {
return false;
}
return true
};
Copy the code
The sum of the left and right subarrays is the same
Given an integer array nums, compute the central index of the array. The central index of an array is an index of the array whose sum of the elements on the left equals the sum of the elements on the right. If the center subscript is at the far left end of the array, the sum of the left numbers is treated as zero, because there is no element to the left of the subscript. This is also true if the center index is at the far right end of the array. If the array has more than one central index, the one closest to the left should be returned. If the array does not have a central index, return -1.Copy the code
Input: nums = [1,7,3,6,5,6] output: 3 explanation: the central subscript is 3. Sum = nums[0] + NUMs [1] + NUMs [2] = 1 + 7 + 3 = 11, sum = nums[4] + NUMs [5] = 5 + 6 = 11. Input: nums = [1, 2, 3] Output: -1 Description: The array does not have a central index that meets this condition. Input: nums = [2, 1, -1] Output: 0 Description: The center subscript is 0. Sum = 0, (there is no element to the left of the subscript 0), sum = nums[1] + nums[2] = 1 + -1 = 0.Copy the code
class Solution {
public static void main(String[] args){
pivoIndex([1.7.3.6.5.6]);
}
public int pivoIndex(int[] nums) {
int[] preSum = new int[nums.length + 1];
for(int i = 0; i < nums.length; i++) { preSum[i +1] = preSum[i] + nums[i];
}
int res = -1;
int tmp = 0;
for(int i = nums.length - 1; i >=0; i--) {if(preSum[i] == tmp) {
res = i
}
tmp += nums[i]
}
returnres; }}Copy the code
The stairs cost the least
Each subscript of the array is a ladder, and the ith ladder corresponds to a non-negative cost cost[I] (the subscript starts at 0). Every time you climb a ladder, you have to spend your stamina. Once you've paid your stamina, you can choose to climb one ladder or two. Please find the lowest cost to reach the top of the floor. To start, you can choose to start with an element with subscript 0 or 1.Copy the code
Input: cost = [10, 15, 20] Output: 15 Explanation: The lowest cost is to start at cost[1] and then walk two steps to the top of the ladder, which costs 15 in total.Copy the code
Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1] Output: 6 Explanation: The lowest cost is to start at cost[0], pass through the ones one by one, skip cost[3], and cost 6 altogether.Copy the code
var minCostClimbingStairs = function(cost) {
if(cost.length<2) {if(cost.length === 1) {return cost[0]}else{
return Math.min(cost[1],cost[0])
}
}
cost.push(0)
let dp=Array(cost.length);
dp[0]=cost[0],dp[1]=cost[1]
for(let i=2; i<cost.length; i++){ dp[i]=Math.min(dp[i-1],dp[i-2]) + cost[i]
}
return dp[cost.length-1]};Copy the code