876. Middle of the Linked List
问题
Given the head of a singly linked list, return the middle node of the linked list.If there are two middle nodes, return the second middle node.
快慢指针,两个指针不同速度遍历链表。当快指针达到链表尾部时候,慢指针正好在中间。
1 | /** |
876. Middle of the Linked List
问题
Given the head of a singly linked list, return the middle node of the linked list.If there are two middle nodes, return the second middle node.
快慢指针,两个指针不同速度遍历链表。当快指针达到链表尾部时候,慢指针正好在中间。
1 | /** |
问题
Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties:
- Integers in each row are sorted from left to right.
- The first integer of each row is greater than the last integer of the previous row.
二分搜索,以整个数组尺寸作为搜索范围。
每次搜索中间值,如等于target则返回。
1 | class Solution { |
双指针,先搜索到合适的行。
再搜索到合适的列。
1 | class Solution { |
问题
Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
- Each row must contain the digits 1-9 without repetition.
- Each column must contain the digits 1-9 without repetition.
- Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition.
Note:
- A Sudoku board (partially filled) could be valid but is not necessarily solvable.
- Only the filled cells need to be validated according to the mentioned rules.
遍历并创建三组不同的哈希表,每个表内包含一组哈希集合。
如果访问的元素已在哈希集合内,则返回false
1 | class Solution { |
Given an integer array arr, and an integer target, return the number of tuples i, j, k such that i < j < k and arr[i] + arr[j] + arr[k] == target.
As the answer can be very large, return it modulo 109 + 7.
首先遍历元素,根据元素的值和出现次数建立哈希表。
然后再哈希表中选择三个元素,如果和等于target,则计算三个元素出现次数的乘积。
最后除以重复计算的次数。
由于数值较大,因此中途计算应该采用长整型long。
1 | class Solution { |
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
两数组相等时,直接遍历两个数组并记录各个字符出现的数量。
一个数组遍历时用做加法,另一个做减法。
如果最后每个字符出现的数量均为0,则返回真。
1 | class Solution { |