public class Solution {
public boolean hasCycle(ListNode head) {
if (head==null || head.next==null) return false;
ListNode fast = head.next;
ListNode slow = head;
while(slow!=fast){
if (fast==null || fast.next ==null) return false;
fast = fast.next.next;
slow = slow.next;
}
return true;
}
}
class Solution {
public boolean isValid(String s) {
Stack<Character> st = new Stack<>();
for (int i=0;i<s.length();i++){
if (s.charAt(i)=='('){
st.push(')');
}else if (s.charAt(i)=='['){
st.push(']');
}else if (s.charAt(i)=='{'){
st.push('}');
}else if (st.isEmpty() || st.peek()!=s.charAt(i)){
return false;
}else{
st.pop();
}
}
return st.isEmpty();
}
}
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root==null || p==root || q==root) return root;
TreeNode left = lowestCommonAncestor(root.left,p,q);
TreeNode right = lowestCommonAncestor(root.right,p,q);
if (left==null && right==null){
return null;
}else if (left!=null && right==null){
return left;
}else if (right!=null && left==null){
return right;
}else{
return root;
}
}
}
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
int cur = m+n-1;
int index1 = m-1;
int index2 = n-1;
while(index1>=0 && index2>=0){
if (nums1[index1]>=nums2[index2]){
nums1[cur] = nums1[index1];
cur--;
index1--;
}else if (nums1[index1]<nums2[index2]){
nums1[cur] = nums2[index2];
cur--;
index2--;
}
}
while(index1>=0) {
nums1[cur] = nums1[index1];
cur--;
index1--;
}
while(index2>=0){
nums1[cur] = nums2[index2];
cur--;
index2--;
}
}
}
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
int[] array = new int[m+n];
int index1 = 0;
int index2 = 0;
int cur = 0;
while(index1<m && index2<n){
if (nums1[index1]<=nums2[index2]){
array[cur++] = nums1[index1++];
}else{
array[cur++] = nums2[index2++];
}
}
while(index1<m){
array[cur++] = nums1[index1++];
}
while(index2<n){
array[cur++] = nums2[index2++];
}
for (int i=0;i<m+n;i++){
nums1[i] = array[i];
}
}
}
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
boolean[] used;
public List<List<Integer>> permute(int[] nums) {
used = new boolean[nums.length];
backtracking(nums,used);
return result;
}
public void backtracking(int[] nums,boolean[] used){
if (path.size()==nums.length){
result.add(new ArrayList<>(path));
return;
}
for (int i=0;i<nums.length;i++){
if (!used[i]){
used[i] = true;
path.add(nums[i]);
backtracking(nums,used);
used[i] = false;
path.removeLast();
}
}
}
}