肯定不是遍历一遍O(N),这种变相有序,也是二分。二分也不容易啊,要思考。
public class LC11 {
public static int minArray(int[] numbers) {
int i=0,j=numbers.length-1;
//用 i 和 m比较的问题是,如果没有旋转数组,会输出最后一个数字 而不是第一个数字
/*
while(inumbers[m]){
j=m;
}else{
i++;
}
}
*/
while(i<j){
int m=(i+j)/2;
if(numbers[j]>numbers[m]){
j=m;
}else if(numbers[j]<numbers[m]){
i=m+1;
}else{
j--;
}
}
return numbers[i];
}
public static void main(String[] args) {
int[] numbers={3,4,5,1,2};
int[] numbers1={2,2,2,0,1};
int[] numbers2={1,2,2}; //因为这种案例,所以在相等的情况下是J--而不是i++
System.out.println(minArray(numbers));
}
}
public class LC12 {
public static void main(String[] args) {
String word="ABCCED";
char[][] borad={{'A','B','C','E'},{'S','F','C','S'},{'A','D','E','E'}};
String word1="abcd";
char[][] board={{'a','b'},{'c','d'}};
System.out.println(exist(borad,word));
}
public static boolean exist(char[][] board, String word) {
char[] words=word.toCharArray();
for(int i=0;i<board.length;i++){
for(int j=0;j<board[0].length;j++){
if(dfs(board,words,i,j,0)) return true;
}
}
return false;
}
public static boolean dfs(char[][] board, char[] word, int i, int j, int k) {
//如果越界 或者 不相等
if(i>=board.length || i<0 || j<0 || j>=board[0].length || word[k]!=board[i][j]) return false;
if(k==word.length-1) return true;
//将走过的位置置空
board[i][j]='\0';
boolean ans=dfs(board,word,i+1,j,k+1) || dfs(board,word,i-1,j,k+1) ||
dfs(board,word,i,j-1,k+1) || dfs(board,word,i,j+1,k+1);
board[i][j]=word[k];
return ans;
}
}
public class Lc13 {
public static void main(String[] args) {
System.out.println(movingCount(2,3,1));
}
public static int movingCount(int m, int n, int k) {
boolean[][] visited = new boolean[m][n];
return dfs(0, 0, m, n, k, visited);
}
public static int dfs(int i,int j,int m,int n,int k,boolean[][]visited) {
if (i < 0 || i > m - 1 || j < 0 || j > n - 1 || j / 10 + j % 10 + i / 10 + i % 10 > k || visited[i][j]) {
return 0;
}
visited[i][j] = true;
return 1 + dfs(i, j - 1, m, n, k, visited) + dfs(i, j + 1, m, n, k, visited) + dfs(i - 1, j, m, n, k, visited) + dfs(i + 1, j, m, n, k, visited);
}
}
所有的dfs都是从每一个点开始,往所有方向遍历,dfs的参数列表还要传一个全局的数组去判断合不合适继续往下走。
n&(n−1) 解析: 二进制数字 n 最右边的 1 变成 0 ,其余不变。
public class Solution {
public int hammingWeight(int n) {
int res = 0;
while(n != 0) {
res++;
n &= n - 1;
}
return res;
}
}
或者直接调用Integer.bitCount(n)函数详解
先处理负数,然后要提前处理奇数。其实最后当b==1的时候也要处理奇数。
class Solution {
public double myPow(double x, int n) {
if(x == 0) return 0;
long b = n;
double res = 1.0;
if(b < 0) {
x = 1 / x;
b = -b;
}
while(b > 0) {
if((b & 1) == 1) res *= x;
x *= x;
b >>= 1;
}
return res;
}
}
class Solution {
public ListNode deleteNode(ListNode head, int val) {
if(head==null) return null;
if(head.val==val) return head.next;
ListNode pre=head,cur=head.next;
while(cur!=null && cur.val!=val){
pre=pre.next;
cur=cur.next;
}
if(cur!=null) pre.next=cur.next;
return head;
}
}