35. 搜索插入位置
二分查找注意下标:
class Solution { public int searchInsert(int[] nums, int target) { int n = nums.length; if(n == 0) return 0; int start = 0, end = n-1; int mid = (end - start)/2 + start; while(end > start){ if(nums[mid] > target){ end = mid - 1; }else if(nums[mid] < target){ start = mid + 1; }else return mid; mid = (end - start)/2 + start; } return nums[mid] >= target ? mid : mid+1; } }
785. 判断二分图
可以使用dfs和bfs,以及并查集
前两个遍历图给图上色,如果存在一个节点上了两种颜色则不是二分图
java dfs
public boolean isBipartite(int[][] graph) { int[] visited = new int[graph.length]; for (int i = 0; i < graph.length; i++) { if(visited[i] == 0 && !dfs(graph, i, 1, visited)) return false; } return true; } public boolean dfs(int[][]graph, int v, int color, int[]visted){ if(visted[v] != 0){ return visted[v] == color; } visted[v] = color; for (int x : graph[v]) { if(!dfs(graph, x, -color, visted)) return false; } return true; }
bfs
public boolean isBipartite(int[][] graph) { int[] visited = new int[graph.length]; Queue<Integer> queue = new LinkedList<Integer>(); for (int i = 0; i < graph.length; i++) { if(visited[i] != 0){ continue; } queue.offer(i); visited[i] = 1; while(!queue.isEmpty()){ int v = queue.poll(); for(int x : graph[v]){ if(visited[x] == visited[v]){ return false; } if (visited[x] == 0){ visited[x] = -visited[v]; queue.offer(x); } } } } return true; }
并查集 概念