LeedCode题目

486. Predict the Winner

package leedcode;
public class PredictTheWinner486 {
  public boolean PredictTheWinner(int[] nums) {
    if(nums.length == 1) {
      return true;
    }
    int dp[][] = new int[nums.length][nums.length];
     int sum[] = new int[nums.length];
     for(int i = 0; i < nums.length; i++) {
       if(i == 0) {
         sum[i] = nums[i];
       } else {
         sum[i] = sum[i-1] + nums[i];
       }
     }
     int maxValue = calculateMaxValue(0, nums.length-1, nums, sum, dp);
     int anotherMaxValue = sum[nums.length-1] - maxValue;
     if(maxValue >= anotherMaxValue) {
       return true;
     }
     return false;
  }
  /**
   * calculateMaxValue 表示计算区间[left,right]中最优的选择,设为 Result, 则sum[left, right]-result为另外一个选手的选择.
   * @param left 下标从0开始
   * @param right  下标
   * @param sum  累加和
   * @return 区间[from, end] 中先选者所能得到的最大值.
   */
  public int calculateMaxValue(int left, int right, int nums[], int[] sum, int dp[][]) {
    //初始化为0
    if(dp[left][right] != 0) {
      return dp[left][right];
    }
    int choseLeftNumberResult;
    int choseRightNumberResult;
    if(left+1 == right) {
      return Math.max(nums[left], nums[right]);
    } else {
      //选择左边的数
      choseLeftNumberResult = nums[left] + (sum[right]-sum[left]-calculateMaxValue(left+1, right, nums, sum, dp));
      int index = left == 0 ? 0 : left-1;
      //选择右边的数
      choseRightNumberResult = nums[right] + (sum[right-1]-sum[index] - calculateMaxValue(left, right-1, nums, sum, dp));
    }
    //记忆化结果.避免重复计算.
    return dp[left][right] = Math.max(choseLeftNumberResult, choseRightNumberResult);
  }

  public static void main(String argc[]) {
    int []nums = {1, 5, 2};
    PredictTheWinner486 obj = new PredictTheWinner486();
    boolean res = obj.PredictTheWinner(nums);
    System.out.print(res);
  }
}

63. Unique Paths II

public class UniquePathsII {
  public static  void main(String argc[]) {
    UniquePathsII obj = new UniquePathsII();
    int[][] path = {
        {0, 0, 0},
        {0, 1, 0},
        {0, 0, 0}
    };
    int pathNum = obj.uniquePathsWithObstacles(path);
    System.out.println(pathNum);
  }
  public int uniquePathsWithObstacles(int[][] obstacleGrid) {
    int rowSize = obstacleGrid.length;
    int colSize = obstacleGrid[0].length;
    for(int row = 0; row < rowSize; row++) {
      for(int col = 0; col < colSize; col++) {
        if(obstacleGrid[row][col] == 1) {
          obstacleGrid[row][col] = -1;
        }
      }
    }
    for(int col = 0; col < colSize; col++) {
      if(obstacleGrid[0][col] == -1) {
        for(int i = col+1; i < colSize; i++) {
          obstacleGrid[0][i] = -1;
        }
        break;
      } else {
        obstacleGrid[0][col] = 1;
      }
    }
    for(int row = 0; row < rowSize; row++) {
      if(obstacleGrid[row][0] == -1) {
        for(int j = row+1; j < rowSize; j++) {
          obstacleGrid[j][0] = -1;
        }
        break;
      } else {
        obstacleGrid[row][0] = 1;
      }
    }
    for(int row = 1; row < rowSize; row++) {
      for(int col = 1; col < colSize; col++) {
        if(obstacleGrid[row][col] == -1) {
          continue;
        } else {
           obstacleGrid[row][col] += obstacleGrid[row-1][col] == -1 ? 0 : obstacleGrid[row-1][col] ;
           obstacleGrid[row][col] += obstacleGrid[row][col-1] == -1 ? 0 : obstacleGrid[row][col-1];
        }
      }
    }
    return obstacleGrid[rowSize-1][colSize-1] == -1 ? 0 : obstacleGrid[rowSize-1][colSize-1];
  }
}

62Unique Paths
思路:先确定第一行和第一列, 以此递推即可。

public class UniquePaths {
  public static void main(String argc[]) {
    UniquePaths obj = new UniquePaths();
    int result = obj.uniquePaths(7, 3);
    System.out.println(result);
  }
  // n * m
  public int uniquePaths(int m, int n) {
    int [][]grid = new int[n][m];
    for(int col = 0; col < m; col++) {
      grid[0][col] = 1;
    }
    for(int row = 0; row < n; row++) {
      grid[row][0] = 1;
    }
    for(int row = 1; row < n; row++) {
      for(int col = 1; col < m; col++) {
        grid[row][col] = grid[row-1][col] +  grid[row][col-1];
      }
    }
    return grid[n-1][m-1];
  }
}

56. Merge Intervals

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

class Interval implements Comparable{
  int start;
  int end;
  Interval() {
    start = 0;
    end = 0;
  }
  Interval(int s, int e) {
    start = s;
    end = e;
  }
  public int getStart() {
    return start;
  }
  public int getEnd() {
    return end;
  }
  public void setStart(int start) {
    this.start = start;
  }
  public void setEnd(int end) {
    this.end = end;
  }

  public int compareTo(Interval o) {
    if(this.start < o.start) {
      return -1;
    } else if(this.start > o.start) {
      return 1;
    } else {
      if(this.end < o.end) {
        return -1;
      } else {
      if(this.end > o.end) {
          return  1;
        }
      }
    }
    return 0;
  }
}

public class Solution {
  public static  void main(String argc[]) {
    //test
  }
  public List merge(List intervals) {
    Collections.sort(intervals);
    List resultList = new ArrayList<>();
    for(Interval element : intervals) {
       if(resultList.isEmpty()) {
         resultList.add(element);
       } else {
         int size = resultList.size();
         Interval lastElement = resultList.get(size-1);
         if(element.start > lastElement.end) {
           resultList.add(element);
         } else if(element.start <= lastElement.end && element.end > lastElement.end) {
           lastElement.setEnd(element.getEnd());
         }
       }
    }
    return resultList;
  }
}

Partition List

class ListNode {
 int val;
 ListNode next;
 ListNode(int x) {
   val = x;
 }
}
  public ListNode partition(ListNode head, int x) {
    if(head == null) {
      return null;
    }
    ListNode newHeadNode = null;
    ListNode lastNode = null;
    for (ListNode it = head;; it = it.next) {
      if(it == null){
        break;
      }
      if(it.val < x) {
        if(newHeadNode == null) {
          newHeadNode = new ListNode(it.val);
          lastNode = newHeadNode;
        } else {
          lastNode.next = new ListNode(it.val);
          lastNode = lastNode.next;
        }
      }
    }
    if(lastNode == null) {
      return head;
    }
    for(ListNode it = head;; it = it.next) {
      if(it == null) {
        break;
      }
      if(it.val >= x) {
        lastNode.next = new ListNode(it.val);
        lastNode = lastNode.next;
      }
    }
    return newHeadNode;
  }

Sort Colors

  public void sortColors(int[] nums) {
    int redNum = 0, whiteNum = 0, blueNum = 0;
    for(int i = 0; i < nums.length; i++) {
      if(nums[i] == 0) {
        redNum++;
      } else if(nums[i] == 1) {
        whiteNum++;
      } else {
        blueNum++;
      }
    }
    int index = 0;
    for(int i = 0; i < redNum; i++) {
      nums[index++] = 0;
    }
    for(int i = 0; i < whiteNum; i++) {
      nums[index++] = 1;
    }
    for(int i = 0; i < blueNum; i++) {
      nums[index++] = 2;
    }
  }

设计并实现一个LRU Cache: https://songlee24.github.io/2015/05/10/design-LRU-Cache/
[LeetCode]146. LRU Cache 深入浅出讲解和代码示例:https://blog.csdn.net/karen0310/article/details/75039604
https://www.cnblogs.com/lzrabbit/p/3734850.html
https://www.cnblogs.com/bakari/p/4016318.html

import java.util.*;
class Node {
  int key;
  int value;
  Node next;
  Node pre;
  public Node(int key,int value,Node pre, Node next){
    this.key = key;
    this.value = value;
    this.pre = pre;
    this.next = next;
  }
}

public class LRUCache {
  int capacity;
  int count;//cache size
  Node head;
  Node tail;
  HashMaphm;
  public LRUCache(int capacity) { //only initial 2 Node is enough, head/tail
    this.capacity = capacity;
    this.count = 2;
    this.head = new Node(-1,-1,null,null);
    this.tail = new Node(-2,-1,this.head,null);
    this.head.next = this.tail;
    hm = new HashMap();
    hm.put(this.head.key, this.head);
    hm.put(this.tail.key, this.tail);
  }

  public int get(int key) {
    int value = -1;
    if(hm.containsKey(key)){
      Node nd = hm.get(key);
      value = nd.value;
      if(nd.pre != null) {
        detachNode(nd); //detach nd from current place
        insertToHead(nd); //insert nd into head
      }
    }
    return value;
  }

  public void put(int key, int value) {
    if(hm.containsKey(key)){ //update
      Node nd = hm.get(key);
      nd.value = value;
      //move to head
      if(nd.pre != null) {
        detachNode(nd); //detach nd from current place
        insertToHead(nd); //insert nd into head
      }
    }else{
      //capacity = 1的特殊处理.
      if(capacity == 1) {
        hm.remove(this.head.key);
        this.head.key = key;
        this.head.value = value;
        hm.put(key, this.head);
        return;
      }
      Node newNd = new Node(key,value,null,this.head);
      this.head.pre = newNd; //insert into head
      this.head = newNd;
      hm.put(key, newNd); //add into hashMap
      this.count ++;
      if(this.count > capacity){ //need delete node
        removeNode();
      }
    }
  }
  //common func
  public void insertToHead(Node nd){
    this.head.pre = nd;
    nd.next = this.head;
    nd.pre = null;
    this.head = nd;
  }

  public void detachNode(Node nd){
    nd.pre.next = nd.next;
    if(nd.next!=null){
      nd.next.pre = nd.pre;
    }else{
      this.tail = nd.pre;
    }
  }

  public void removeNode(){ //remove from tail
    int tailKey = this.tail.key;
    this.tail = this.tail.pre;
    this.tail.next = null;
    hm.remove(tailKey);
    this.count --;
  }
  public void printCache(){
    System.out.println("\nPRINT CACHE ------ ");
    System.out.println("count: "+count);
    System.out.println("From head:");
    Node p = this.head;
    while(p!=null){
      System.out.println("key: "+p.key+" value: "+p.value);
      p = p.next;
    }
    System.out.println("From tail:");
    p = this.tail;
    while(p!=null){
      System.out.println("key: "+p.key+" value: "+p.value);
      p = p.pre;
    }

  }

  public static void main(String[] args) {
    LRUCache lc = new LRUCache(1);
    lc.put(2,1);
    lc.printCache();;
    lc.get(2);
    lc.printCache();
    lc.put(3,2);
    lc.printCache();
    System.out.println(lc.get(2));
    System.out.println(lc.get(3));
    lc.printCache();
  }
}

你可能感兴趣的:(LeetCode)