项目作者: royalghost

项目描述 :
Code Samples
高级语言: Java
项目地址: git://github.com/royalghost/code_samples.git
创建时间: 2018-03-10T02:27:43Z
项目社区:https://github.com/royalghost/code_samples

开源协议:

下载


Code Samples

Remove Duplicates from a Sorted List

This is a medium level question from LeetCode

  1. static ListNode deleteDuplicates(ListNode head) {
  2. ListNode current = head;
  3. ListNode dummy = new ListNode(0);
  4. dummy.next = head;
  5. ListNode previous = dummy;
  6. while (current != null && current.next != null) {
  7. if (current.val == current.next.val) {
  8. while (current.next != null && current.val == current.next.val) {
  9. current = current.next;
  10. }
  11. previous.next = current.next;
  12. } else {
  13. previous = current;
  14. }
  15. current = current.next;
  16. }
  17. return dummy.next;
  18. }

View full implementation

Keys and Rooms

Question - https://leetcode.com/problems/keys-and-rooms/

  1. public boolean canVisitAllRooms(List<List<Integer>> rooms) {
  2. //This is a depth first search problem
  3. //Solved by using a Stack and keeping track of each node visited or not in order to avoid infinite loop
  4. if ( rooms == null || rooms.isEmpty() ) return true;
  5. final int N = rooms.size();
  6. //keep track of each node if visited or not with each node set to false initially
  7. boolean visits[] = new boolean[N];
  8. //Since by problem definition first one is unlocked so can visit without key
  9. visits[0] = true;
  10. Stack<List<Integer>> roomStack = new Stack<>();
  11. //Add the list of rooms for which keys are available on first node
  12. roomStack.push(rooms.get(0));
  13. while (! roomStack.isEmpty() ){
  14. List<Integer> keysInRoom = roomStack.pop();
  15. //Iterate through each key found in the node
  16. for(Integer key : keysInRoom){
  17. if ( ! visits[ key ] ) {
  18. visits[key] = true;
  19. roomStack.push( rooms.get( key) );
  20. }
  21. }
  22. }
  23. //check if all visited is true or not
  24. for(boolean visit : visits)
  25. if (!visit) return false;
  26. return true;
  27. }

View full implementation