Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.
Example 1:
Input: nums = [-4,-1,0,3,10] Output: [0,1,9,16,100] Explanation: After squaring, the array becomes [16,1,0,9,100]. After sorting, it becomes [0,1,9,16,100]. Example 2:
Reverse String Solved Easy Topics premium lock icon Companies Hint Write a function that reverses a string. The input string is given as an array of characters s.
You must do this by modifying the input array in-place with O(1) extra memory.
Example 1:
Input: s = [“h”,”e”,”l”,”l”,”o”] Output: [“o”,”l”,”l”,”e”,”h”] Example 2:
Input: s = [“H”,”a”,”n”,”n”,”a”,”h”] Output: [“h”,”a”,”n”,”n”,”a”,”H”]
Constraints:
1 <= s.length <= 105 s[i] is a printable ascii character.
// 示例 2 char[] s2 = {'H','a','n','n','a','h'}; sol.reverseString(s2); System.out.println(java.util.Arrays.toString(s2)); // 输出: [h, a, n, n, a, H] } }
🧮 执行过程演示
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
以 s = ['h','e','l','l','o'] 为例:
初始: h e l l o ↑ ↑ left right
第1轮: 交换 s[0]='h' 和 s[4]='o' o e l l h ↑ ↑ left right
第2轮: 交换 s[1]='e' 和 s[3]='l' o l l e h ↑ left=right → 结束
结果: [o, l, l, e, h] ✅
💡 核心要点
双指针 • 说明: 左右夹逼,逐步交换
终止条件 • 说明: left >= right 时停止
为什么原地 • 说明: 只用了 temp 一个变量,O(1) 空间
时间复杂度 • 说明: O(n/2) = O(n)
这是最简单的双指针入门题,也是面试高频热身题 🔥
leetcode 15
3Sum Medium Topics premium lock icon Companies Hint Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
Notice that the solution set must not contain duplicate triplets.
Example 1:
Input: nums = [-1,0,1,2,-1,-4] Output: [[-1,-1,2],[-1,0,1]] Explanation: nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0. nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0. nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0. The distinct triplets are [-1,0,1] and [-1,-1,2]. Notice that the order of the output and the order of the triplets does not matter. Example 2:
Input: nums = [0,1,1] Output: [] Explanation: The only possible triplet does not sum up to 0. Example 3:
Input: nums = [0,0,0] Output: [[0,0,0]] Explanation: The only possible triplet sums up to 0.