141 Linked List Cycle
Approach 1: Hash Table
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
Set<ListNode> set= new HashSet<>();
while(head!=null){
if(set.contains(head)) return true;
else{
set.add(head);
}
head=head.next;
}
return false;
}
}
Approach 2: Two Pointers
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
if(head==null||head.next==null) return false;
ListNode slow = head;
ListNode fast = head.next;
while(fast!=slow){
if(fast==null||fast.next==null) return false;
slow=slow.next;
fast=fast.next.next;
}
return true;
}
}
206. Reverse Linked List
Approach #1 (Iterative) [Accepted]
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev=null;
ListNode curr=head;
while(curr!=null){
ListNode nextTemp=curr.next;
curr.next=prev;
prev=curr;
curr=nextTemp;
}
return prev;
}
}
Approach #2 (Recursive)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null||head.next==null) return head;
ListNode p=reverseList(head.next);
head.next.next=head;
head.next=null;
return p;
}
}
24. Swap Nodes in Pairs
recursion
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
if(head==null||head.next==null) return head;
ListNode n=head.next;
head.next=swapPairs(head.next.next);
n.next=head;
return n;
}
}
25. Reverse Nodes in k-Group
recursive:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if (k==0) return head;
ListNode curr =head;
int count=0;
while(curr!=null&&count<k){
curr=curr.next;
count++;
}
if(count==k){
curr=reverseKGroup(curr,k);
while(count-->0){
ListNode temp=head.next;
head.next=curr;
curr=head;
head=temp;
}
head=curr;
}
return head;
}
}
142. Linked List Cycle II
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
if(head==null||head.next==null) return null;
ListNode fast=head;
ListNode slow=head;
while(fast!=null&&fast.next!=null){
fast=fast.next.next;
slow=slow.next;
if(fast==slow){
slow=head;
while(slow!=fast){
slow=slow.next;
fast=fast.next;
}
return slow;
}
}
return null;
}
}
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
if(head==null||head.next==null) return null;
Set<ListNode> nodeset =new HashSet<ListNode>();
while(head!=null){
if(nodeset.contains(head)) return head;
nodeset.add(head);
head=head.next;
}
return null;
}
}
20. Valid Parentheses
class Solution {
public boolean isValid(String s) {
Stack<Character> stack =new Stack<>();
for(char c:s.toCharArray()){
if(c=='('||c=='['||c=='{') stack.push(c);
else if(c==')'&&!stack.empty()&& stack.peek()=='(') stack.pop();
else if(c==']'&&!stack.empty()&& stack.peek()=='[') stack.pop();
else if(c=='}'&&!stack.empty()&& stack.peek()=='{') stack.pop();
else return false;
}
return stack.empty();
}
}
232. Implement Queue using Stacks
class MyQueue {
Stack<Integer> input= new Stack<>();
Stack<Integer> output=new Stack<>();
/** Initialize your data structure here. */
public MyQueue() {
}
/** Push element x to the back of queue. */
public void push(int x) {
input.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
peek();
return output.pop();
}
/** Get the front element. */
public int peek() {
if(output.empty()) {
while(!input.empty()){
output.push(input.pop());
}
}
return output.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return input.empty()&&output.empty();
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/
225. Implement Stack using Queues
class MyStack {
Queue<Integer> queue=new LinkedList<>();
/** Initialize your data structure here. */
public MyStack() {
}
/** Push element x onto stack. */
public void push(int x) {
queue.add(x);
for(int i=1;i<queue.size();i++)
queue.add(queue.remove());
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return queue.remove();
}
/** Get the top element. */
public int top() {
return queue.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return queue.isEmpty();
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/
703. Kth Largest Element in a Stream
class KthLargest {
final PriorityQueue<Integer> q;
final int k;
public KthLargest(int k, int[] nums) {
this.k=k;
q=new PriorityQueue<>(k);
for(int i:nums) add(i);
}
public int add(int val) {
if(q.size()<k) q.offer(val);
else if(q.peek()<val){
q.poll();
q.offer(val);
}
return q.peek();
}
}
/**
* Your KthLargest object will be instantiated and called as such:
* KthLargest obj = new KthLargest(k, nums);
* int param_1 = obj.add(val);
*/
239. Sliding Window Maximum
Java O(n) solution using deque
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
if(nums==null||k<=0) return new int[0];
int[] result=new int[nums.length-k+1];
Deque<Integer> q=new ArrayDeque<>();
int ri=0;
for(int i=0;i<nums.length;i++){
while(!q.isEmpty()&&q.peekFirst()<i-k+1)
q.poll();
while(!q.isEmpty()&&nums[q.peekLast()]<nums[i])
q.pollLast();
q.add(i);
if(i>=k-1) result[ri++]=nums[q.peekFirst()];
}
return result;
}
}
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
if(nums==null||k<=0) return new int[0];
int[] result =new int[nums.length-k+1];
int ri=0;
final PriorityQueue<Integer> q=new PriorityQueue<>(
new Comparator<Integer>(){
@Override
public int compare(Integer o1,Integer o2){
return Integer.compare(o2,o1);
}
}
);
for(int i=0;i<k;i++){
q.offer(nums[i]);
}
result[ri++]=q.peek();
for(int i=k;i<nums.length;i++){
q.remove(nums[i-k]);
q.offer(nums[i]);
result[ri++]=q.peek();
}
return result;
}
}
242. Valid Anagram
(Sorting)
class Solution {
public boolean isAnagram(String s, String t) {
if(s.length()!=t.length()) return false;
char[] str1=s.toCharArray();
char[] str2=t.toCharArray();
Arrays.sort(str1);
Arrays.sort(str2);
return Arrays.equals(str1,str2);
}
}
Hash Table
class Solution {
public boolean isAnagram(String s, String t) {
if(s.length()!=t.length()) return false;
int[] table =new int[26];
for(int i=0;i<s.length();i++){
table[s.charAt(i)-'a']++;
}
for(int i=0;i<t.length();i++){
table[t.charAt(i)-'a']--;
if(table[t.charAt(i)-'a']<0) return false;
}
return true;
}
}
class Solution {
public boolean isAnagram(String s, String t) {
if(s.length()!=t.length()) return false;
Map<Character,Integer> m=new HashMap<>();
for(int i=0;i<s.length();i++){
char c=s.charAt(i);
if(m.containsKey(c)){
Integer k=m.get(c);
k=k+1;
m.put(c,k);
}
else{
m.put(c,1);
}
}
for(int i=0;i<t.length();i++){
char c=t.charAt(i);
if(!m.containsKey(c)) return false;
else{
Integer k=m.get(c);
if(k==1) m.remove(c);
else{
k=k-1;
m.put(c,k);
}
}
}
return true;
}
}
1. Two Sum
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> m=new HashMap<>();
int[] res=new int[2];
for(int i=0;i<nums.length;i++){
if(m.containsKey(target-nums[i])){
res[0]=i;
res[1]=m.get(target-nums[i]);
return res;
}
m.put(nums[i],i);
}
return res;
}
}
15. 3Sum
Linkedlist O(n2)
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res =new LinkedList<>();
if(nums==null||nums.length<3) return res;
Arrays.sort(nums);
// List<Integer> temp=new List<>();
int i=0;
while(i<nums.length-2){
if(nums[i]>0) break;
int j=i+1;
int k=nums.length-1;
while(j<k){
int sum=nums[i]+nums[j]+nums[k];
if(sum==0) res.add(Arrays.asList(nums[i],nums[j],nums[k]));
if(sum<=0) while(nums[j]==nums[++j]&&j<k);
if(sum>=0) while(nums[k]==nums[--k]&&j<k);
}
while(nums[i]==nums[++i]&&i<nums.length-2);
}
return res;
}
}
98. Validate Binary Search Tree
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isValidBST(TreeNode root) {
return isValid(root,null,null);
}
public boolean isValid(TreeNode root,Integer min,Integer max){
if(root==null) return true;
if((min!=null&&root.val<=min)||(max!=null&&root.val>=max)) return false;
return isValid(root.left,min,root.val)&&isValid(root.right,root.val,max);
}
}
Approach 3: Inorder traversal
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isValidBST(TreeNode root) {
if(root==null) return true;
Stack<TreeNode> stack =new Stack<>();
double pre =-Double.MAX_VALUE;
while(root!=null||!stack.isEmpty()){
while(root!=null){
stack.push(root);
root=root.left;
}
root=stack.pop();
if(root.val<=pre) return false;
pre=root.val;
root=root.right;
}
return true;
}
}
236. Lowest Common Ancestor of a Binary Tree
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root==null||root==p||root==q) return root;
TreeNode left=lowestCommonAncestor(root.left,p,q);
TreeNode right=lowestCommonAncestor(root.right,p,q);
return left==null?right:right==null?left:root;
}
}
235. Lowest Common Ancestor of a Binary Search Tree
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root.val>p.val&&root.val>q.val) return lowestCommonAncestor(root.left,p,q);
else if(root.val<p.val&&root.val<q.val) return lowestCommonAncestor(root.right,p,q);
else return root;
}
}
50. Pow(x, n)
O (logn)
class Solution {
public double myPow(double x, int n) {
if(n == 0)
return 1;
if(n<0){
n = -n;
x = 1/x;
}
if(-n<=Integer.MIN_VALUE) return x*myPow(x,n-1); //解决边界溢出的问题
return (n%2 == 0) ? myPow(x*x, n/2) : x*myPow(x*x, n/2);
}
}
二分快速幂(logn)
class Solution {
public double myPow(double x, int n) {
int exp;
double res=1,curr=x;
if(n>0) exp=n;
else if(n<0) {
if(x==0) throw new RuntimeException("分母不能为0");
exp=-n;
}
else return 1;
while(exp!=0){
if((exp&1)==1) res*=curr;
exp>>=1;
curr*=curr;
}
return n>0?res:1/res;
}
}
169. Majority Element
Approach 1: Brute Force
class Solution {
public int majorityElement(int[] nums) {
int majoritylength=nums.length/2;
for(int i=0;i<nums.length;i++){
int count=1;
for(int j=i+1;j<nums.length;j++){
if(nums[i]==nums[j])
count++;
}
if(count>majoritylength) return nums[i];
}
return -1;
}
}
Approach 3: Sorting
class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length/2];
}
}
class Solution {
public int majorityElement(int[] nums) {
Map<Integer,Integer> m=new HashMap<>();
Integer k;
for(int i=0;i<nums.length;i++){
if(m.containsKey(nums[i])){
k=m.get(nums[i])+1;
}
else
k=1;
if(k>nums.length/2) return nums[i];
m.put(nums[i],k);
}
return -1;
}
}
122. Best Time to Buy and Sell Stock II
贪心:O(n)
class Solution {
public int maxProfit(int[] prices) {
int total=0;
for(int i=0;i<prices.length-1;i++){
if(prices[i+1]>prices[i]) total+=prices[i+1]-prices[i];
}
return total;
}
}
遍历比较 O(n)
class Solution {
public int maxProfit(int[] prices) {
int i=0,buy,sell,total=0;
while(i<prices.length-1){
while (i<prices.length-1 && prices[i+1]<prices[i]) i++; //注意边界条件,一不小心就出错
buy=prices[i];
while(i<prices.length-1 && prices[i+1]>=prices[i]) i++;
sell=prices[i];
total+=sell-buy;
}
return total;
}
}