在这里插入代码片
# leetcode sqrt(x)
Implement int sqrt(int x).
Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
Exmple:
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842…, and since
the decimal part is truncated, 2 is returned.
Binary Search
二分探索法
public int sqrt(int x) {
if (x == 0)
return 0;
int left = 1, right = Integer.MAX_VALUE;//right = x;
while (true) {
int mid = left + (right - left)/2;
if (mid > x/mid) {
right = mid - 1;
} else {
if (mid + 1 > x/(mid + 1))
return mid;
left = mid + 1;
}
}
}
Newton Solution
public int sqrt(int x){
if(x=0) return 0;
int r = x;
while(r*r>x){
r=(r+x/r)/2;
}
return r ;
}
Brute Force
Brute Force Algorithms refers to a programming style that does not include any shortcuts to improve performance, but instead relies on sheer computing power to try all possibilities until the solution to a problem is found
public int mySqrt(int x) {
if(x==0) return 0;
for(int i=1;i<=x/2;i++){
if(i*i>x) return i-1;
}
return 0;
}
70.leetcode Climbing Stairs
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Example
Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
- 1 step + 1 step + 1 step
- 1 step + 2 steps
- 2 steps + 1 step
class Solution {
public int climbStairs(int n) {
int i=3;
int sum =0;
int k = 0;
while(n-i>0){
k=n-i;
sum+=(k*k+k)/2;
i+=2;
}
sum+=n;
return sum;
}
}
例
5だとすると
0個2を選ぶとき:1
1個2を選ぶとき:5-1
2個2を選ぶとき:2+1
6だとすると
0個2を選ぶとき:1
1個2を選ぶとき:6-1
2個2を選ぶとき:3+2+1
3個2を選ぶとき:1
标准的思想是斐波那契汤
public class Solution {
public int climbStairs(int n) {
int[] dp = new int[n + 1];
if (n == 1) {
return 1;
}
if (n == 2) {
return 2;
}
dp[0] = 0;
dp[1] = 1;
dp[2] = 2;
for (int i = 3; i <= n; i++) {
dp[i] = dp[i-1] + dp[i - 2];
}
return dp[n];
}
}
数据结构分类
1、数组
2、栈
3、队列
4、链表
5、树
6、散列表
7、堆
8、图
71.leetcode
Example
Input: “/home/”
Output: “/home”
Explanation: Note that there is no trailing slash after the last directory name.
反斜杠
Input: “/home//foo/”
Output: “/home/foo”
Explanation: In the canonical path, multiple consecutive slashes are replaced by a single one.
连续斜线
public String simplifyPath(String path) {
Stack<String> stack = new Stack<>();
String[] p = path.split("/");
for (int i = 0; i < p.length; i++) {
if (!stack.empty() && p[i].equals(".."))
stack.pop();
else if (!p[i].equals(".") && !p[i].equals("") && !p[i].equals(".."))
stack.push(p[i]);
}
List<String> list = new ArrayList(stack);
return "/"+String.join("/", list);
}
public String simplifyPath(String path) {
Deque<String> stack = new LinkedList<>();
Set<String> skip = new HashSet<>(Arrays.asList("..",".",""));
for (String dir : path.split("/")) {
if (dir.equals("..") && !stack.isEmpty()) stack.pop();
else if (!skip.contains(dir)) stack.push(dir);
}
String res = "";
for (String dir : stack) res = "/" + dir + res;
return res.isEmpty() ? "/" : res;
}
73.leetcode Set Matrix Zeroes
Example
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.
class Solution {
public void setZeroes() {
int row=matrix.length-1;
int co=matrix[0].length-1;
int[][] array2=new int[row+1][co+1];
for(int i = 0;i < matrix.length;i++){
array2[i] = matrix[i].clone();
}
for(int i=0;i<=row;i++){
for(int j=0;j<=co;j++){
if(matrix[i][j]==0){
for(int m=0;m<=co;m++) array2[i][m]=0;
for(int m=0;m<=row;m++) array2[m][j]=0;
}
}
}
// for(int i=0;i<=row;i++){
// for(int j=0;j<=co;j++){
// System.out.print(array2[i][j]);
// }
// }
//return 1;
}
}
矩阵遍历找到为0的坐标,记录坐标;
对应坐标将第i行第j列全部置0;
问题:
必须复制一个相同的二维数组,占用空间
class Solution {
public void setZeroes() {
int row=matrix.length-1;
int co=matrix[0].length-1;
int[][] index= new int[row][2];
int k=0;
for(int i=0;i<=row;i++){
for(int j=0;j<=co;j++){
if(matrix[i][j]==0){
index[k][0]=i;
index[k++][1]=j;
}
}
}
for(int i=0;i<k;i++){
for(int m=0;m<=co;m++) matrix[index[i][0]][m]=0;
for(int m=0;m<=row;m++) matrix[m][index[i][1]]=0;
}
}
}
新建数组存储坐标
根据坐标进行遍历原二维数组并修改
void setZeroes(vector<vector<int> > &matrix) {
int col0 = 1, rows = matrix.size(), cols = matrix[0].size();
for (int i = 0; i < rows; i++) {
if (matrix[i][0] == 0) col0 = 0;
for (int j = 1; j < cols; j++)
if (matrix[i][j] == 0)
matrix[i][0] = matrix[0][j] = 0;
}
for (int i = rows - 1; i >= 0; i--) {
for (int j = cols - 1; j >= 1; j--)
if (matrix[i][0] == 0 || matrix[0][j] == 0)
matrix[i][j] = 0;
if (col0 == 0) matrix[i][0] = 0;
}
}
leetcode 74. Search a 2D Matrix
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int row = matrix.length-1;
int col=matrix[0].length-1;
boolean flag=false;
for(int i=0;i<=row;i++){
if(target>=matrix[i][0]&&target<matrix[i+1][0]||i==row&&target>=matrix[row][0]){
for(int j=0;j<=col;j++){
if(target==matrix[i][j]) {flag=true;break;}
}
}
}
return flag;
}
}
想要用二分法:
列寻找不好用
行寻找可以用
er
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int row = matrix.length-1;
int col=matrix[0].length-1;
boolean flag=false;
int front=0;
int mid=(front+col)/2;
int bot=col;
for(int i=0;i<=row;i++){
if(target>=matrix[i][0]&&target<matrix[i+1][0]||i==row&&target>=matrix[row][0]){
while(front<=bot){
if(target>matrix[i][mid]){front=mid;mid =(front+bot)/2;}
else if(target<matrix[i][mid]){bot=mid;mid =(front+bot)/2;}
else if(target==matrix[i][mid]){flag=true;break;}
}
}
}
return flag;
}
}
public boolean searchMatrix(int[][] matrix, int target) {
int i = 0, j = matrix[0].length - 1;
while (i < matrix.length && j >= 0) {
if (matrix[i][j] == target) {
return true;
} else if (matrix[i][j] > target) {
j--;
} else {
i++;
}
}
return false;
}
- Simplify Path
Given an absolute path for a file (Unix-style), simplify it. Or in other words, convert it to the canonical path.
In a UNIX-style file system, a period . refers to the current directory. Furthermore, a double period … moves the directory up a level. For more information, see: Absolute path vs relative path in Linux/Unix
Note that the returned canonical path must always begin with a slash /, and there must be only a single slash / between two directory names. The last directory name (if it exists) must not end with a trailing /. Also, the canonical path must be the shortest string representing the absolute path.
class Solution {
public String simplifyPath(String path) {
int i=path.length;
string[] patha=path.split("/",0);
Stack<character> str = new Stack<character>();
while(patha>0){//如何得知个数
if(patha[i]=="..") str.pop();
else if(patha[i]=="..") ;
else str.push(patha[i]) ;
i++;
}
}
}
stack str = new stack();
str.push();
str.pop();
str.empty();
80. Remove Duplicates from Sorted Array II
class Solution {
public int removeDuplicates(int[] nums) {
int j=1;
int result=0;
for(int i=1;i<=nums.length-1;i++){
if(j<2&&nums[i]==nums[i-1]){
j++;
}
else if(nums[i]!=nums[i-1]){
result+=j;
j=1;
}
}
System.out.print(result +j);
return result +j;
}
}
remove的api不可用
但是不允许创建新的数组
可以理解为对无法实现删除数据元素
1 转化为链表实现
2 对个数计算只输出数字
public int removeDuplicates(int[] nums) {
int i = 0;
for (int n : nums)
if (i < 2 || n > nums[i-2])
nums[i++] = n;
return i;
}
最后直接用的覆盖
public ListNode partition(ListNode head, int x) {
ListNode small = new ListNode(0);
ListNode start= small;
while (head!=null&&head.val<x) {small.next=head; small=small.next;head=head.next;}
ListNode big = head;
while(head!=null){
if(head.next!=null&&head.next.val<x){
small.next=head.next;
small=small.next;
head.next=head.next.next;
}
else
head=head.next;
}
small.next=big;
return start.next;
}
左移n-1位
1<<(n-1)
2^(n-1)