Grind 169 - week 1

Ace your homework & exams now with Quizwiz!

141. Linked List Cycle Given a linked list, determine if it has a cycle in it.

快慢指针法: 两个指针,每当慢指针slow前进一步,快指针fast就前进两步。如果fast最终遇到空指针,说明链表里没有环;如果fast最终和slow相遇,那肯定是fast超过了slow一圈,说明链表中有环

232. Implement Queue using Stacks

用两个stacks s1, s2就能实现queue的功能。 1. push:将元素压入s1实现push的功能 2. peek/pop:若s2为空,可以把s1所有元素取出压入s2,这时候s2的元素就是先进先出了

二叉树的前序遍历

List<Integer> res = new LinkedList<>(); // 返回前序遍历结果 List<Integer> preorder(TreeNode root){ traverse(root); return res; } // 二叉树遍历函数 void traverse(TreeNode root){ if (root == null) { return; } // 前序遍历位置 res.addLast(root.val); traverse(root.left); traverse(root.right); }

278. First Bad Version You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad. Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad. You are given an API bool isBadVersion(version) which returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.

二分法,low = 0, high = n, mid = low + (high - low)/2; public class Solution extends VersionControl { public int firstBadVersion(int n) { int low = 0, high = n; while(low <= high){ int mid = low + (high - low)/2; if (isBadVersion(mid) == true && isBadVersion(mid - 1) == false) return mid; else if(isBadVersion(mid) == false) low = mid + 1; else high = mid; } return -1; } }

110. Balanced Binary Tree

二叉树解题的思维模式: 1. 是否可以通过遍历二叉树得到答案?如果是,通过一个traverse函数配合外部变量来实现。 2. 是否可以定义一个递归函数,通过子问题(子树)的答案推导出原问题的答案?如果可以,写出递归函数的定义,并充分利用这个函数的返回值。

383. Ransom Note Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise. Each letter in magazine can only be used once in ransomNote.

如果ransomNote的长度大于magazine,false; 新建两个长度为26的array,记录两个string中不同字母出现的频次并进行比较。 class Solution { public boolean canConstruct(String ransomNote, String magazine) { if (ransomNote.length() > magazine.length()) return false; int[] alphabets_counter = new int[26]; for (char c : magazine.toCharArray()) alphabets_counter[c - 'a']++; for (char c : ransomNote.toCharArray()){ if (alphabets_counter[c - 'a'] == 0) return false; alphabets_counter[c - 'a']--; } return true; } }


Related study sets

Chapter 45 (Drugs for Diabetes Mellitus) Practice Questions

View Set

Hesi Quiz: Evidence-Based Practice/Evidence

View Set

ENDOCRINE/GI&NUTRITION/INFECTIOUS DX/URINARY-Pediatrics

View Set

CISSP Information Security and Risk Management (Set 1)

View Set