leetcode71.Simplify Path
题目要求
1 | Given an absolute path for a file (Unix-style), simplify it. |
简化unix风格的绝对路径。
这里简单说一下unix风格的路径:
.表示当前文件夹,即不进行任何操作..表示返回上层文件夹,如果已经至根目录,则不进行任何操作/表示路径的分割线,多个连续的/等价于/
这里我们需要将复杂的unix路径,例如/a/./b/../../c/简化成最简形式/c
1 | Given an absolute path for a file (Unix-style), simplify it. |
简化unix风格的绝对路径。
这里简单说一下unix风格的路径:
.表示当前文件夹,即不进行任何操作..表示返回上层文件夹,如果已经至根目录,则不进行任何操作/表示路径的分割线,多个连续的/等价于/这里我们需要将复杂的unix路径,例如/a/./b/../../c/简化成最简形式/c
1 | Validate if a given string is numeric. |
写一个算法 判断输入的字符串是否是数字。
这道题的需求给的较为模糊,对于什么是数字并没有给出明确的定义。这里我要给出几个特殊的情况来说明数字究竟是什么。
1 | Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue. |
假设一个数组中存在3个数字0,1,2。将数组中的数字排序,尽量实现O(n)时间复杂度。
1 | Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: |
假设存在这样一个二维数组,该数组从左到右,从上到下均递增,且下一行第一个值比上一行最后一个值大。要求从里面找到一个目标值,存在则返回true,否则返回false
熟悉二分法的知道,在一个有序的一维数组中,可以只用O(lgn)的时间复杂度就可以从中判读出目标值是否存在。我们可以先对第一列上的值进行一次二分法遍历,确定了行后再在行中进行第二次的二分法遍历。总计的时间复杂度为O(lgn),代码如下:
1 | public boolean searchMatrix(int[][] matrix, int target) { |
如何能之间在二维数组上使用二分法呢。其实只要我们找到相应的左指针和右指针以及其对应的中间位置上的值即可。其实这个二维数组完全可以看成一个连续的一维数组,位于二维数组[i,j]位置可以看成一维数组中下标为[i*column+j].由此我们知道,左右指针对应中间节点在二维数组的下标为[mid/column][mid%column]。代码如下:
1 | public boolean searchMatrix2(int[][] matrix, int target){ |
1 | Follow up for "Remove Duplicates": |
Remove Duplicates I 可以参考我的这篇博客
这题中添加了一个要求,就是允许存在两个重复值。
1 | The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other. |
1 | Given an integer n, return all distinct solutions to the n-queens puzzle. |
这里的王后相当于国际围棋的王后,该王后一共有三种移动方式:水平、垂直,对角线。问要如何将n个王后布局在n*n的棋盘中保证她们不会互相伤害捏?
1 | Given a set of distinct integers, nums, return all possible subsets. |
类似的题目有:
leetcode60 Permutation Sequence 可以参考这篇博客
leetcode77 Combinations 可以参考这篇博客
1 | Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. |
将小于x的值放在前面,大于等于x的值放在后面,移动的过程中不改变数字之间的相对顺序。