第18章---高度难题

1,-------另类加法。实现加法。

  1. 另类加法
  2. 参与人数:327时间限制:3秒空间限制:32768K
  3. 算法知识视频讲解
  4. 题目描述
  5. 请编写一个函数,将两个数字相加。不得使用+或其他算数运算符。
  6. 给定两个int AB。请返回AB的值
  7. 测试样例:
  8. 1,2
  9. 返回:3

答案和思路:xor是相加不进位。and得到每一个地方的进位。所以,用and<<1之后去与xor异或。不断递归。

  1. import java.util.*;
  2. public class UnusualAdd {
  3. public int addAB(int a, int b) {
  4. // write code here
  5. if (b == 0) {
  6. return a;
  7. }
  8. int xor = a ^ b;
  9. int and = a & b;
  10. and = and << 1;
  11. return addAB(xor, and);
  12. }
  13. }

 

 

 

 

 

 

 

 

第17章中等难度的题

1,--------无缓存交换

  1. 请编写一个函数,函数内不使用任何临时变量,直接交换两个数的值。
  2. 给定一个int数组AB,其第零个元素和第一个元素为待交换的值,请返回交换后的数组。
  3. 测试样例:
  4. [1,2]
  5. 返回:[2,1]

答案:注意,用异或来做一定要判断是否相等。不然就是0了。记忆:左边a,b,a,右边都是a^b。

  1. import java.util.*;
  2. public class Exchange {
  3. public int[] exchangeAB(int[] AB) {
  4. // write code here
  5. if (AB[0] == AB[1]) {
  6. return AB;
  7. }
  8. AB[0] = AB[0] ^ AB[1];
  9. AB[1] = AB[0] ^ AB[1];
  10. AB[0] = AB[0] ^ AB[1];
  11. return AB;
  12. }
  13. }

2,----------井字游戏

  1. 题目描述
  2. 对于一个给定的井字棋棋盘,请设计一个高效算法判断当前玩家是否获胜。
  3. 给定一个二维数组board,代表当前棋盘,其中元素为1的代表是当前玩家的棋子,为0表示没有棋子,为-1代表是对方玩家的棋子。
  4. 测试样例:
  5. [[1,0,1],[1,-1,-1],[1,-1,0]]
  6. 返回:true

答案:

  1. import java.util.*;
  2. public class Board {
  3. public boolean checkWon(int[][] board) {
  4. // write code here
  5. for (int i = 0; i < 3; ++i) {
  6. if (board[i][0] == 1 && board[i][1] == 1 && board[i][2] == 1) {
  7. return true;
  8. }
  9. }
  10. for (int j = 0; j < 3; ++j) {
  11. if (board[0][j] == 1 && board[1][j] == 1 && board[2][j] == 1) {
  12. return true;
  13. }
  14. }
  15. if (board[0][0] == 1 && board[1][1] == 1 && board[2][2] == 1) {
  16. return true;
  17. }
  18. if (board[0][2] == 1 && board[1][1] == 1 && board[2][0] == 1) {
  19. return true;
  20. }
  21. return false;
  22. }
  23. }

 3,----------阶乘尾0的个数

  1. Factorial Trailing Zeroes My Submissions QuestionEditorial Solution
  2. Total Accepted: 57385 Total Submissions: 175529 Difficulty: Easy
  3. Given an integer n, return the number of trailing zeroes in n!.
  4. Note: Your solution should be in logarithmic time complexity.
  5. Credits:
  6. Special thanks to @ts for adding this problem and creating all test cases.
  7. Subscribe to see which companies asked this question

答案和思路:注意这里面如果i是int会越界导致WA。改为了long

  1. public class Solution {
  2. public int trailingZeroes(int n) {
  3. if (n < 0) {
  4. return -1;
  5. }
  6. int count = 0;
  7. for (long i = 5; n / i > 0; i *= 5) {
  8. count += n / i;
  9. }
  10. return count;
  11. }
  12. }

 4,--------------无判断max

  1. 无判断max
  2. 参与人数:499时间限制:3秒空间限制:32768K
  3. 本题知识点: 编程基础
  4. 算法知识视频讲解
  5. 题目描述
  6. 请编写一个方法,找出两个数字中最大的那个。条件是不得使用if-else等比较和判断运算符。
  7. 给定两个int ab,请返回较大的一个数。若两数相同则返回任意一个

答案和解析:利用好abs

  1. import java.util.*;
  2. public class Max {
  3. public int getMax(int a, int b) {
  4. // write code here
  5. return ((a + b) + Math.abs(a - b)) / 2;
  6. }
  7. }

 5,------------珠玑妙算

  1. 题目描述
  2. 我们现在有四个槽,每个槽放一个球,颜色可能是红色(R)、黄色(Y)、绿色(G)或蓝色(B)。例如,可能的情况为RGGB(槽1为红色,槽23为绿色,槽4为蓝色),作为玩家,你需要试图猜出颜色的组合。比如,你可能猜YRGB。要是你猜对了某个槽的颜色,则算一次“猜中”。要是只是猜对了颜色但槽位猜错了,则算一次“伪猜中”。注意,“猜中”不能算入“伪猜中”。
  3. 给定两个string Aguess。分别表示颜色组合,和一个猜测。请返回一个int数组,第一个元素为猜中的次数,第二个元素为伪猜中的次数。
  4. 测试样例:
  5. "RGBY","GGRR"
  6. 返回:[1,1]

答案和思路:猜中的话直接来统计。顺便建立list。

  1. import java.util.*;
  2. public class Result {
  3. public int[] calcResult(String A, String B) {
  4. // write code here
  5. int[] res = new int[2];
  6. if (A == null || A.length() == 0 || B == null || B.length() == 0) {
  7. return res;
  8. }
  9. ArrayList<Character> listA = new ArrayList();
  10. ArrayList<Character> listB = new ArrayList();
  11. for (int i = 0; i < A.length(); ++i) {
  12. if (A.charAt(i) == B.charAt(i)) {
  13. res[0]++;
  14. }
  15. listA.add(A.charAt(i));
  16. listB.add(B.charAt(i));
  17. }
  18. for(Character c : listB) {
  19. if (listA.contains(c)) {
  20. res[1]++;
  21. listA.remove(c);
  22. }
  23. }
  24. res[1] -= res[0];
  25. return res;
  26. }
  27. }

6,----------最小调整有序

  1. 题目描述
  2. 有一个整数数组,请编写一个函数,找出索引mn,只要将mn之间的元素排好序,整个数组就是有序的。注意:n-m应该越小越好,也就是说,找出符合条件的最短序列。
  3. 给定一个int数组A和数组的大小n,请返回一个二元组,代表所求序列的起点和终点。(原序列位置从0开始标号,若原序列有序,返回[0,0])。保证A中元素均为正整数。
  4. 测试样例:
  5. [1,4,6,5,9,10],6
  6. 返回:[2,3]

答案和思路:左边看过去的时候,如果他是他以后的最小,那么就从他后面开始。右边max就行。

  1. import java.util.*;
  2. public class Rearrange {
  3. public int[] findSegment(int[] A, int n) {
  4. // write code here
  5. int[] res = new int[2];
  6. for (int i = 0; i <= A.length - 1; ++i) {
  7. res[0] = i;
  8. if (!isMin(A, i, i, A.length - 1)) {
  9. break;
  10. }
  11. }
  12. if (res[0] == A.length - 1) {
  13. res[0] = 0;
  14. return res;
  15. }
  16. for (int i = A.length - 1; i > 0; --i) {
  17. res[1] = i;
  18. if (!isMax(A, i, 0 , i)) {
  19. break;
  20. }
  21. }
  22. return res;
  23. }
  24. public static boolean isMin(int[] A, int k, int start, int end) {
  25. for (int i = start; i <= end; ++i) {
  26. if (A[i] < A[k]) {
  27. return false;
  28. }
  29. }
  30. return true;
  31. }
  32. public static boolean isMax(int[] A, int k, int start, int end) {
  33. for (int i = start; i <= end; ++i) {
  34. if (A[i] > A[k]) {
  35. return false;
  36. }
  37. }
  38. return true;
  39. }
  40. }

 7,----数字发音:

  1. 数字发音
  2. 参与人数:125时间限制:3秒空间限制:32768K
  3. 本题知识点: 编程基础
  4. 算法知识视频讲解
  5. 题目描述
  6.  
  7. 有一个非负整数,请编写一个算法,打印该整数的英文描述。
  8. 给定一个int x,请返回一个string,为该整数的英文描述。
  9. 测试样例:
  10. 1234
  11. 返回:"One Thousand,Two Hundred Thirty Four"

答案解答:其实就是不断打表的过程。

  1. import java.util.*;
  2.  
  3. public class ToString {
  4. static String[] belowTen = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
  5. static String[] belowTwenty = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
  6. static String[] belowHundred = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
  7. public static String toString(int x) {
  8. if (x == 0) {
  9. return "Zero";
  10. }
  11. return helper(x);
  12. }
  13. public static String helper(int num) {
  14. String result = "";
  15. if (num < 10) {
  16. result = belowTen[num];
  17. } else if (num < 20) {
  18. result = belowTwenty[num - 10];
  19. } else if (num < 100) {
  20. result = belowHundred[num / 10] + " " + helper(num % 10);
  21. } else if (num < 1000) {
  22. result = helper(num / 100) + " Hundred " + helper(num % 100);
  23. } else if (num < 1000000) {
  24. result = helper(num / 1000) + " Thousand" + (num % 1000 == 0 ? " " : ",") + helper(num % 1000);
  25. } else if (num < 1000000000) {
  26. result = helper(num / 1000000) + " Million" + (num % 1000000 == 0 ? " " : ",") + helper(num % 1000000);
  27. } else {
  28. result = helper(num / 1000000000) + " Billion " + helper(num % 1000000000);
  29. }
  30. return result.trim();
  31. }
  32. }

 

8,---------最大的连续和

  1. 最大连续数列和
  2. 参与人数:425时间限制:3秒空间限制:32768K
  3. 本题知识点: 贪心
  4. 算法知识视频讲解
  5. 题目描述
  6. 对于一个有正有负的整数数组,请找出总和最大的连续数列。
  7. 给定一个int数组A和数组大小n,请返回最大的连续数列的和。保证n的大小小于等于3000
  8. 测试样例:
  9. [1,2,3,-6,1]
  10. 返回:6

答案和思路:dp[i] 表示以i为结尾的最大和。用max记录最大的。

  1. import java.util.*;
  2. public class MaxSum {
  3. public int getMaxSum(int[] A, int n) {
  4. // write code here
  5. if (A == null || A.length == 0) {
  6. return 0;
  7. }
  8. int max = A[0];
  9. int[] dp = new int[A.length];
  10. dp[0] = A[0];
  11. for (int i = 1; i < A.length; ++i) {
  12. if (dp[i - 1] > 0) {
  13. dp[i] = A[i] + dp[i - 1];
  14. } else {
  15. dp[i] = A[i];
  16. }
  17. max = Math.max(max, dp[i]);
  18. }
  19. return max;
  20. }
  21. }

 

 9,------------统计单词出现的频率

牛客网的比较简单:

  1. 返回难题列表
  2. 讨论
  3. 排行
  4. 我的提交
  5. 词频统计
  6. 参与人数:453时间限制:3秒空间限制:32768K
  7. 本题知识点: 编程基础
  8. 算法知识视频讲解
  9. 题目描述
  10. 请设计一个高效的方法,找出任意指定单词在一篇文章中的出现频数。
  11. 给定一个string数组article和数组大小n及一个待统计单词word,请返回该单词在文章中的出现频数。保证文章的词数小于等于1000

答案:注意点:一定要全部变成小写。

  1. import java.util.*;
  2. public class Frequency {
  3. public int getFrequency(String[] article, int n, String word) {
  4. // write code here
  5. if (null == article || article.length == 0) {
  6. return 0;
  7. }
  8. int res = 0;
  9. for (int i = 0; i < article.length; ++i) {
  10. if (article[i].toLowerCase().equals(word)) {
  11. res++;
  12. }
  13. }
  14. return res;
  15. }
  16. }

 

CC150课本的题目的代码:

  1. import java.util.HashMap;
  2. public class WordCount {
  3. public HashMap<String, Integer> wordCount(String[] book) {
  4. // 关键点:要注意单词的大小写要统一变成小写。
  5. HashMap<String, Integer> res = new HashMap();
  6. for (String word : book) {
  7. word = word.toLowerCase();
  8. if (!word.trim().equals("")) {
  9. if (res.containsKey(word)) {
  10. res.put(word, res.get(word) + 1);
  11. } else {
  12. res.put(word, 1);
  13. }
  14. }
  15. }
  16. return res;
  17. }
  18. }

 

 

11,-------------随机数构造。rand5() => rand7()

思路:randN() => randM()。

rangdN()*N + randN()。这样的话就能一直是等概率的产生。条件一前面的加起来要大于randM()。然后只取他的整数倍。之所以*N,是因为为了+randN()的时候,刚好能放进去0,1,...,N-1.

 

  1. public static int rand7() {
  2. while (true) {
  3. int num = rand5() * 5 + rand5();
  4. if (num < 21) {
  5. return num % 7;
  6. }
  7. }
  8. }

 

12,-------------整数对个数查找

  1. 整数对查找
  2. 参与人数:350时间限制:3秒空间限制:32768K
  3. 本题知识点: 编程基础
  4. 算法知识视频讲解
  5. 题目描述
  6. 请设计一个高效算法,找出数组中两数之和为指定值的所有整数对。
  7. 给定一个int数组A和数组大小n以及需查找的和sum,请返回和为sum的整数对的个数。保证数组大小小于等于3000
  8. 测试样例:
  9. [1,2,3,4,5],5,6
  10. 返回:2

思路:难点1在于如何构建hashmap。因为有重复元素,所以,元素,个数是K-V。难点2在于,如果a[i] == sum - a[i]。这时候用的是C n 2.然后其他情况的话就是直接相乘即可。注意点:用了就要remove。

答案:

  1. import java.util.*;
  2. public class FindPair {
  3. public int countPairs(int[] A, int n, int sum) {
  4. // write code here
  5. HashMap<Integer, Integer> map = new HashMap();
  6. for (int i = 0; i < n; ++i) {
  7. if (map.containsKey(A[i])) {
  8. map.put(A[i], map.get(A[i]) + 1);
  9. } else {
  10. map.put(A[i], 1);
  11. }
  12. }
  13. int count = 0;
  14. for (int i = 0; i < n; ++i) {
  15. if (map.containsKey(sum - A[i])) {
  16. if (A[i] == sum - A[i]) {
  17. count += (map.get(A[i]) * (map.get(A[i]) - 1) / 2);
  18. map.remove(A[i]);
  19. continue;
  20. }
  21. count += map.get(A[i]) * map.get(sum - A[i]);
  22. map.remove(A[i]);
  23. map.remove(sum - A[i]);
  24. }
  25. }
  26. return count++;
  27. }
  28. }

也可以用for循环暴力:

  1. import java.util.*;
  2. public class FindPair {
  3. public int countPairs(int[] A, int n, int sum) {
  4. int count = 0;
  5. for(int i=0;i<n;i++){
  6. for(int j=i+1;j<n;j++){
  7. if(A[i]+A[j]==sum){
  8. count++;
  9. }
  10. }
  11. }
  12. return count;
  13. }
  14. }

 

 第11章:排序和查找

2,-------变位词的排序

  1. 变位词排序
  2. 参与人数:290时间限制:3秒空间限制:32768K
  3. 本题知识点: 字符串 排序 查找
  4. 算法知识视频讲解
  5. 题目描述
  6. 请编写一个方法,对一个字符串数组进行排序,将所有变位词合并,保留其字典序最小的一个串。这里的变位词指变换其字母顺序所构成的新的词或短语。例如"triangle""integral"就是变位词。
  7. 给定一个string的数组str和数组大小int n,请返回排序合并后的数组。保证字符串串长小于等于20,数组大小小于等于300
  8. 测试样例:
  9. ["ab","ba","abc","cba"]
  10. 返回:["ab","abc"]

答案:利用好Arrays的sort。进去之前先排序一次就能够很好的处理了。如果去重变位词的话,利用HashSet。

  1. import java.util.*;
  2. public class SortString {
  3. public ArrayList<String> sortStrings(String[] str, int n) {
  4. // write code here
  5. if (str == null || n == 0) {
  6. return null;
  7. }
  8. ArrayList<String> res = new ArrayList();
  9. Arrays.sort(str);
  10. HashSet<char[]> set = new HashSet();
  11. for (int i = 0; i < n; ++i) {
  12. char[] c = str[i].toCharArray();
  13. Arrays.sort(c);
  14. if (!set.contains(c)) {
  15. set.add(c);
  16. res.add(new String(c));
  17. }
  18. }
  19. return res;
  20. }
  21. }

不去重的话可以重写sort。为了让他变位词那里也都是有序的,可以进去之前先sort一次。

  1. import java.util.*;
  2. public class SortString {
  3. public static void main(String[] args) {
  4. String[] str = {"ab", "abc", "ba", "cba", "acb"};
  5. sortStrings(str, 4);
  6. System.out.println(Arrays.toString(str));
  7. }
  8. public static void sortStrings(String[] str, int n) {
  9. // write code here
  10. Arrays.sort(str);
  11. Arrays.sort(str, new Comparator<String>() {
  12. public int compare(String a, String b) {
  13. char[] c1 = a.toCharArray();
  14. char[] c2 = b.toCharArray();
  15. Arrays.sort(c1);
  16. Arrays.sort(c2);
  17. return new String(c1).compareTo(new String(c2));
  18. }
  19. });
  20. }
  21. }

 

 3,-------旋转数组查找。

答案和思路:还是用二分,不过关键点是在于要判断x是否与于某一个连续不减的区间。

  1. import java.util.*;
  2. public class Finder {
  3. public int findElement(int[] A, int n, int x) {
  4. // write code here
  5. if (null == A || n == 0) {
  6. return -1;
  7. }
  8. int start = 0;
  9. int end = n - 1;
  10. while (start <= end) {
  11. int mid = start + (end - start) / 2;
  12. if (A[mid] == x) {
  13. return mid;
  14. }
  15. if (A[start] <= A[mid]) {
  16. if (x >= A[start] && x <= A[mid]) {
  17. end = mid - 1;
  18. } else {
  19. start = mid + 1;
  20. }
  21. } else {
  22. if (x >= A[mid] && x <= A[end]) {
  23. start = mid + 1;
  24. } else {
  25. end = mid - 1;
  26. }
  27. }
  28. }
  29. return -1;
  30. }
  31. }

 

4,------20GB大文件。如何进行排序。可用内存xM。

答:把文件切成xM大小。然后对每一个都进行排序,拍好后写回文件系统。再逐一合并。这个算法称作外部排序。

5,-------找字符串位置,含有空字符串。找出字符串

  1. 找出字符串
  2. 参与人数:341时间限制:3秒空间限制:32768K
  3. 本题知识点: 排序 查找
  4. 算法知识视频讲解
  5. 题目描述
  6. 有一个排过序的字符串数组,但是其中有插入了一些空字符串,请设计一个算法,找出给定字符串的位置。算法的查找部分的复杂度应该为log级别。
  7. 给定一个string数组str,同时给定数组大小n和需要查找的string x,请返回该串的位置(位置从零开始)。
  8. 测试样例:
  9. ["a","b","","c","","d"],6,"c"
  10. 返回:3

答案和思路:因为含有“”,那么在到了mid的时候找一个和他最近的部位“”来代替他。这次是往左找到头了才开始往右找。优化的话两边都开始同时找。

 

  1. import java.util.*;
  2. public class Finder {
  3. public int findString(String[] str, int n, String x) {
  4. // write code here
  5. if (null == str || n == 0) {
  6. return 0;
  7. }
  8. int left = 0;
  9. int right = n - 1;
  10. while (left <= right) {
  11. int mid = left + (right - left) / 2;
  12. int keep = mid;
  13. while (mid >= left && str[mid].equals("")) {
  14. mid--;
  15. }
  16. if (mid < left) {
  17. mid = keep;
  18. while (mid <= right && str[mid].equals("")) {
  19. mid++;
  20. if (mid > right) {
  21. return -1;
  22. }
  23. }
  24. }
  25. if (str[mid].equals(x)) {
  26. return mid;
  27. }
  28. if (str[mid].compareTo(x) > 0) {
  29. right = mid - 1;
  30. } else {
  31. left = mid + 1;
  32. }
  33. }
  34. return -1;
  35. }
  36. }

 

6,----------矩阵元素查找

  1. 矩阵元素查找
  2. 参与人数:302时间限制:3秒空间限制:32768K
  3. 本题知识点: 排序 查找
  4. 算法知识视频讲解
  5. 题目描述
  6. 有一个NxM的整数矩阵,矩阵的行和列都是从小到大有序的。请设计一个高效的查找算法,查找矩阵中元素x的位置。
  7. 给定一个int有序矩阵mat,同时给定矩阵的大小nm以及需要查找的元素x,请返回一个二元数组,代表该元素的行号和列号(均从零开始)。保证元素互异。
  8. 测试样例:
  9. [[1,2,3],[4,5,6]],2,3,6
  10. 返回:[1,2]

答案和思路:注意,他只是行列都是有序的。但是并不表示一行一行接上去是有序的。和之前的题有不同。所以这里用的是对每一行进行二分。

  1. import java.util.*;
  2. public class Finder {
  3. public int[] findElement(int[][] a, int n, int m, int x) {
  4. // write code here
  5. if (null == a || a.length == 0) {
  6. return null;
  7. }
  8. int[] res = new int[2];
  9. res[0] = -1;
  10. res[1] = -1;
  11. for (int i = 0; i < n; ++i) {
  12. int left = 0;
  13. int right = m - 1;
  14. while (left <= right) {
  15. int mid = left + (right - left) / 2;
  16. if (a[i][mid] == x) {
  17. res[0] = i;
  18. res[1] = mid;
  19. return res;
  20. } else if (a[i][mid] < x) {
  21. left = mid +1;
  22. } else {
  23. right = mid - 1;
  24. }
  25. }
  26. }
  27. return res;
  28. }
  29. }

进一步优化有待改进。利用好列也是有序的。

 

 7,-------叠罗汉

  1. 叠罗汉I
  2. 参与人数:220时间限制:3秒空间限制:32768K
  3. 本题知识点: 动态规划 排序 查找
  4. 算法知识视频讲解
  5. 题目描述
  6. 叠罗汉是一个著名的游戏,游戏中一个人要站在另一个人的肩膀上。同时我们应该让上面的人比下面的人更高一点。已知参加游戏的每个人的身高,请编写代码计算通过选择参与游戏的人,我们多能叠多少个人。注意这里的人都是先后到的,意味着参加游戏的人的先后顺序与原序列中的顺序应该一致。
  7. 给定一个int数组men,代表依次来的每个人的身高。同时给定总人数n,请返回做多能叠的人数。保证n小于等于500
  8. 测试样例:
  9. [1,6,2,5,3,4],6
  10. 返回:4

答案和思路:注意初始化每一位都是1.

  1. import java.util.*;
  2. public class Stack {
  3. public int getHeight(int[] men, int n) {
  4. // write code here
  5. if (null == men || n == 0) {
  6. return 0;
  7. }
  8. int[] dp = new int[n];
  9. Arrays.fill(dp, 1);
  10. int max = dp[0];
  11. for (int i = 1; i < n; ++i) {
  12. for (int j = 0; j < i; ++j) {
  13. if (men[j] < men[i]) {
  14. dp[i] = Math.max(dp[i], dp[j] + 1);
  15. }
  16. }
  17. max = Math.max(max, dp[i]);
  18. }
  19. return max;
  20. }
  21. }

 

7,--------叠罗汉二,身高体重两维

  1. 叠罗汉II
  2. 参与人数:164时间限制:3秒空间限制:32768K
  3. 本题知识点: 动态规划 排序 查找
  4. 算法知识视频讲解
  5. 题目描述
  6.  
  7. 叠罗汉是一个著名的游戏,游戏中一个人要站在另一个人的肩膀上。为了使叠成的罗汉更稳固,我们应该让上面的人比下面的人更轻一点。现在一个马戏团要表演这个节目,为了视觉效果,我们还要求下面的人的身高比上面的人高。请编写一个算法,计算最多能叠多少人,注意这里所有演员都同时出现。
  8. 给定一个二维int的数组actors,每个元素有两个值,分别代表一个演员的身高和体重。同时给定演员总数n,请返回最多能叠的人数。保证总人数小于等于500
  9. 测试样例:
  10. [[,],[,],[,],[,]],
  11. 返回:

答案和思路:重写Arrays.sort().

  1. import java.util.*;
  2.  
  3. public class Stack {
  4. public int getHeight(int[][] actors, int n) {
  5. // write code here
  6. if (null == actors || n == 0) {
  7. return 0;
  8. }
  9. Arrays.sort(actors, new Comparator<int[]>() {
  10. public int compare(int[] a, int[] b) {
  11. if (a[0] > b[0]) {
  12. return -1;
  13. } else if (a[0] == b[0]) {
  14. if (a[1] > b[1]) {
  15. return -1;
  16. } else {
  17. return 1;
  18. }
  19. } else {
  20. return 1;
  21. }
  22. }
  23. });
  24.  
  25. int[] dp = new int[n];
  26. Arrays.fill(dp, 1);
  27. int max = 1;
  28. for (int i = 1; i < n; ++i) {
  29. for (int j = i - 1; j >= 0; --j) {
  30. if (actors[i][0] < actors[j][0] && actors[i][1] < actors[j][1]) {
  31. dp[i] = Math.max(dp[i], dp[j] + 1);
  32. }
  33. }
  34. max = Math.max(max, dp[i]);
  35. }
  36. return max;
  37. }
  38. }

 8,----------维护x的秩,找他前面比他小的数

  1. 维护x的秩
  2. 参与人数:207时间限制:3秒空间限制:32768K
  3. 本题知识点: 高级结构 排序 查找
  4. 算法知识视频讲解
  5. 题目描述
  6.  
  7. 现在我们要读入一串数,同时要求在读入每个数的时候算出它的秩,即在当前数组中小于等于它的数的个数(不包括它自身),请设计一个高效的数据结构和算法来实现这个功能。
  8. 给定一个int数组A,同时给定它的大小n,请返回一个int数组,元素为每次加入的数的秩。保证数组大小小于等于5000
  9. 测试样例:
  10. [1,2,3,4,5,6,7],7
  11. 返回:[0,1,2,3,4,5,6]

答案:注意利用插入来做的时候,如果他要插入的位置是最后的话,要单独考虑。

  1. import java.util.*;
  2.  
  3. public class Rank {
  4. public int[] getRankOfNumber(int[] a, int n) {
  5. if (null == a || n == 0) {
  6. return null;
  7. }
  8. ArrayList<Integer> list = new ArrayList();
  9. int[] res = new int[n];
  10. list.add(a[0]);
  11. res[0] = 0;
  12. for (int i = 1; i < n; ++i) {
  13. int num = 0;
  14. for (int j = 0; j < list.size(); ++j) {
  15. if (a[i] < list.get(j)) {
  16. list.add(j, a[i]);
  17. res[i] = j;
  18. break;
  19. }
  20. if (j == list.size() - 1) {
  21. list.add(j + 1, a[i]);
  22. res[i] = j + 1;
  23. break;
  24. }
  25. }
  26. }
  27. return res;
  28. }
  29. }

 

 

第九章:递归和动态规划

1,上台阶

  1. 上楼梯
  2. 参与人数:700时间限制:3秒空间限制:32768K
  3. 本题知识点: 动态规划 递归
  4. 算法知识视频讲解
  5. 题目描述
  6. 有个小孩正在上楼梯,楼梯有n阶台阶,小孩一次可以上1阶、2阶、3阶。请实现一个方法,计算小孩有多少种上楼的方式。为了防止溢出,请将结果Mod 1000000007
  7. 给定一个正整数int n,请返回一个数,代表上楼的方式数。保证n小于等于100000
  8. 测试样例:
  9. 1
  10. 返回:1

答案:注意溢出。因为n是10亿,三个加起来是30亿,已经溢出了。所以要用long。并且一直%。

  1. import java.util.*;
  2. public class GoUpstairs {
  3. public int countWays(int n) {
  4. // write code here
  5. if (n == 1) {
  6. return 1;
  7. }
  8. if (n == 2) {
  9. return 2;
  10. }
  11. if (n == 3) {
  12. return 4;
  13. }
  14. long[] dp = new long[n];
  15. dp[0] = 1;
  16. dp[1] = 2;
  17. dp[2] = 4;
  18. for (int i = 3; i < n; i++) {
  19. dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3];
  20. dp[i] = dp[i] % 1000000007;
  21. }
  22. return (int)dp[n - 1];
  23. }
  24. }

 

2,机器人走方格

  1. 机器人走方格II
  2. 参与人数:428时间限制:3秒空间限制:32768K
  3. 本题知识点: 高级结构 哈希 队列 链表 字符串 数组 编程基础 复杂度 穷举 模拟 分治 动态规划 贪心 递归 排序 查找
  4. 算法知识视频讲解
  5. 题目描述
  6. 有一个XxY的网格,一个机器人只能走格点且只能向右或向下走,要从左上角走到右下角。请设计一个算法,计算机器人有多少种走法。注意这次的网格中有些障碍点是不能走的。
  7. 给定一个int[][] map(C++ 中为vector >),表示网格图,若map[i][j]为1则说明该点不是障碍点,否则则为障碍。另外给定int x,int y,表示网格的大小。请返回机器人从(0,0)走到(x - 1,y - 1)的走法数,为了防止溢出,请将结果Mod 1000000007。保证xy均小于等于50

答案:注意不要把dp和map弄混了。

  1. import java.util.*;
  2. public class Robot {
  3. public int countWays(int[][] map, int x, int y) {
  4. // write code here
  5. if (map == null || map.length == 0) {
  6. return 0;
  7. }
  8. int[][] dp = new int[x][y];
  9. for (int i = 0; i < x; ++i) {
  10. if (map[i][0] != 1) {
  11. break;
  12. }
  13. dp[i][0] = 1;
  14. }
  15. for (int j = 0; j < y; ++j) {
  16. if (map[0][j] != 1) {
  17. break;
  18. }
  19. dp[0][j] = 1;
  20. }
  21. for (int i = 1; i < x; ++i) {
  22. for (int j = 1; j < y; ++j) {
  23. if (map[i][j] != 1) {
  24. dp[i][j] = 0;
  25. } else {
  26. dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
  27. dp[i][j] = dp[i][j] % 1000000007;
  28. }
  29. }
  30. }
  31. return dp[x - 1][y - 1];
  32. }
  33. }

 

3,魔术索引

  1. 魔术索引I
  2. 参与人数:478时间限制:3秒空间限制:32768K
  3. 本题知识点: 动态规划 递归
  4. 算法知识视频讲解
  5. 题目描述
  6. 在数组A[0..n-1]中,有所谓的魔术索引,满足条件A[i]=i。给定一个升序数组,元素值各不相同,编写一个方法,判断在数组A中是否存在魔术索引。请思考一种复杂度优于o(n)的方法。
  7. 给定一个int数组Aint n代表数组大小,请返回一个bool,代表是否存在魔术索引。
  8. 测试样例:
  9. [1,2,3,4,5]
  10. 返回:false

答案:用二分。

  1. import java.util.*;
  2. public class MagicIndex {
  3. public boolean findMagicIndex(int[] A, int n) {
  4. // write code here
  5. if (A == null || A.length == 0) {
  6. return false;
  7. }
  8. return findMagicIndex(A, 0, n - 1);
  9. }
  10. private boolean findMagicIndex(int[] a, int start, int end) {
  11. if (start > end) {
  12. return false;
  13. }
  14. int mid = (start + end) / 2;
  15. if (a[mid] == mid) {
  16. return true;
  17. } else if (a[mid] > mid) {
  18. end = mid - 1;
  19. } else {
  20. start = mid + 1;
  21. }
  22. return findMagicIndex(a, start, end);
  23. }
  24. }

魔术索引二:如果有重复元素怎么办。那么久暴力的方式,但是如果A[i] > i 了。那么i至少从A[i]开始找。

  1. import java.util.*;
  2. public class MagicIndex {
  3. public boolean findMagicIndex(int[] A, int n) {
  4. // write code here
  5. if (null == A || A.length == 0) {
  6. return false;
  7. }
  8. for (int i = 0; i < A.length; ++i) {
  9. if (A[i] == i) {
  10. return true;
  11. } else if (A[i] > i) {
  12. i = A[i];
  13. } else {
  14. i++;
  15. }
  16. }
  17. return false;
  18. }
  19. }

 

4,-----------集合的所有子集

  1. 集合的子集
  2. 参与人数:320时间限制:3秒空间限制:32768K
  3. 本题知识点: 动态规划 贪心 递归 排序 查找
  4. 算法知识视频讲解
  5. 题目描述
  6. 请编写一个方法,返回某集合的所有非空子集。
  7. 给定一个int数组A和数组的大小int n,请返回A的所有非空子集。保证A的元素个数小于等于20,且元素互异。各子集内部从大到小排序,子集之间字典逆序排序,见样例。
  8. 测试样例:
  9. [123,456,789]
  10. 返回:{[789,456,123],[789,456],[789,123],[789],[456 123],[456],[123]}

答案和思路:还是利用来一个插入一个的思想来做。但是因为要全部逆序,所以,要注意插入的方式是从后往前,而且是在原有集合的基础上插入的时候把他放到他前面。

  1. import java.util.ArrayList;
  2. import java.util.Arrays;
  3. public class Subset {
  4. public static ArrayList<ArrayList<Integer>> getSubsets(int[] a, int n) {
  5. ArrayList<ArrayList<Integer>> res = new ArrayList();
  6. Arrays.sort(a);
  7. for (int i = n - 1; i >= 0; --i) {
  8. ArrayList<ArrayList<Integer>> temp = new ArrayList();
  9. for (ArrayList<Integer> list : res) {
  10. ArrayList<Integer> tempList = new ArrayList(list);
  11. ArrayList<Integer> list2 = new ArrayList(list);
  12. tempList.add(a[i]);
  13. temp.add(tempList);
  14. temp.add(list2);
  15. }
  16. ArrayList<Integer> now = new ArrayList();
  17. now.add(a[i]);
  18. temp.add(now);
  19. res = new ArrayList(temp);
  20. System.out.println(res);
  21. }
  22. return res;
  23. }
  24. }

 

 5,-------------字符串的全排列

  1. 字符串排列
  2. 参与人数:386时间限制:3秒空间限制:32768K
  3. 本题知识点: 动态规划 递归
  4. 算法知识视频讲解
  5. 题目描述
  6. 编写一个方法,确定某字符串的所有排列组合。
  7. 给定一个string A和一个int n,代表字符串和其长度,请返回所有该字符串字符的排列,保证字符串长度小于等于11且字符串中字符均为大写英文字符,排列中的字符串按字典序从大到小排序。(不合并重复字符串)
  8. 测试样例:
  9. "ABC"
  10. 返回:["CBA","CAB","BCA","BAC","ACB","ABC"]

答案:

  1. import java.util.ArrayList;
  2. import java.util.Arrays;
  3. import java.util.Collections;
  4. import java.util.Comparator;
  5. public class Permutation {
  6. public static ArrayList<String> getPermutation(String A) {
  7. // write code here
  8. ArrayList<StringBuffer> res = new ArrayList();
  9. ArrayList<String> finalRes = new ArrayList();
  10. char[] c = A.toCharArray();
  11. Arrays.sort(c);
  12. StringBuffer start = new StringBuffer();
  13. start.append(c[c.length - 1]);
  14. res.add(start);
  15. System.out.println(res);
  16. for (int i = c.length - 2; i >= 0; --i) {
  17. ArrayList<StringBuffer> temp = new ArrayList();
  18. for (StringBuffer sb : res) {
  19. for (int j = 0; j <= sb.length(); ++j) {
  20. StringBuffer tempSb = new StringBuffer(sb);
  21. tempSb.insert(j, c[i]);
  22. temp.add(tempSb);
  23. }
  24. }
  25. res = new ArrayList(temp);
  26. }
  27. for (int i = 0; i < res.size(); ++i) {
  28. finalRes.add(new String(res.get(i)));
  29. }
  30. Collections.sort(finalRes, new Comparator<String>() {
  31. public int compare(String a, String b) {
  32. for (int i = 0; i < a.length() && i < b.length(); ++i) {
  33. if (a.charAt(i) < b.charAt(i)) {
  34. return 1;
  35. } else if (a.charAt(i) > b.charAt(i)) {
  36. return -1;
  37. }
  38. }
  39. if (a.length() > b.length()) {
  40. return -1;
  41. } else {
  42. return 1;
  43. }
  44. }
  45. });
  46. System.out.println(finalRes);
  47. return finalRes;
  48. }
  49. }

 

 6,---------合法的括号()串

  1. 合法括号序列判断
  2. 参与人数:159时间限制:3秒空间限制:32768K
  3. 本题知识点: 字符串 编程基础
  4. 算法知识视频讲解
  5. 题目描述
  6. 对于一个字符串,请设计一个算法,判断其是否为一个合法的括号串。
  7. 给定一个字符串A和它的长度n,请返回一个bool值代表它是否为一个合法的括号串。
  8. 测试样例:
  9. 返回:true
  10. 测试样例:
  11. 返回:false
  12. 测试样例:
  13. 返回:false

答案和思路:利用stack来做。

  1. import java.util.*;
  2. public class Parenthesis {
  3. public boolean chkParenthesis(String A, int n) {
  4. // write code here
  5. if (A == null || A.length() == 0) {
  6. return false;
  7. }
  8. if (A.length() % 2 == 1) {
  9. return false;
  10. }
  11. Stack<Character> stack = new Stack();
  12. for (int i = 0; i < A.length(); ++i) {
  13. if (stack.isEmpty() && A.charAt(i) == ')') {
  14. return false;
  15. }
  16. if (A.charAt(i) == ')') {
  17. if (stack.pop() == '(') {
  18. } else {
  19. return false;
  20. }
  21. } else if (A.charAt(i) == '(') {
  22. stack.add('(');
  23. } else {
  24. return false;
  25. }
  26. }
  27. return true;
  28. }
  29. }

 附上打印括号的程序:

  1. import java.util.ArrayList;
  2. public class Main {
  3. public static void main(String[] args) {
  4. System.out.println(generateParens(6));
  5. }
  6. public static ArrayList<String> generateParens(int count) {
  7. char[] str = new char[count * 2];
  8. ArrayList<String> list = new ArrayList();
  9. addParen(list, count, count, str, 0);
  10. return list;
  11. }
  12. public static void addParen(ArrayList<String> list, int leftNum, int rightNum, char[] str, int index) {
  13. if (leftNum < 0 || rightNum < leftNum) {
  14. return;
  15. }
  16. if (leftNum == 0 && rightNum == 0) {
  17. String s = String.copyValueOf(str);
  18. list.add(s);
  19. } else {
  20. if (leftNum > 0) {
  21. str[index] = '(';
  22. addParen(list, leftNum - 1, rightNum, str, index + 1);
  23. }
  24. if (rightNum > leftNum) { // 注意这里
  25. str[index] = ')';
  26. addParen(list, leftNum, rightNum - 1, str, index + 1);
  27. }
  28. }
  29. }
  30. }

 

7,-------将新颜色填入这个点周围区域。

 

 

8,-----------硬币组合

  1. 硬币表示
  2. 参与人数:326时间限制:3秒空间限制:32768K
  3. 本题知识点: 动态规划 递归
  4. 算法知识视频讲解
  5. 题目描述
  6. 有数量不限的硬币,币值为25分、10分、5分和1分,请编写代码计算n分有几种表示法。
  7. 给定一个int n,请返回n分有几种表示法。保证n小于等于100000,为了防止溢出,请将答案Mod 1000000007
  8. 测试样例:
  9. 6
  10. 返回:2

答案和思路:利用好对于新加入面值他影响的就是他到他减去面试的dp[i] + 1 ,表示从i这里出发,它能够多一种组合方式。

  1. import java.util.*;
  2. public class Coins {
  3. public int countWays(int n) {
  4. // write code here
  5. int[] dp = new int[n + 1];
  6. // 思路:当只有1的时候算出来了一种解法。那么来了5的时候,他前面的+5可以构成他,
  7. // 那么就多了这一种。然后加上它本身1的时候就有的种类。
  8. int[] coins = {1, 5, 10, 25};
  9. dp[0] = 1;
  10. for (int i = 0; i < 4; ++i) {
  11. for (int j = coins[i]; j < n + 1; ++j) {
  12. dp[j] = (dp[j] + dp[j - coins[i]]) % 1000000007;
  13. }
  14. }
  15. return dp[n];
  16. }
  17. }

 

 9,----------n皇后问题

  1. n皇后问题
  2. 参与人数:237时间限制:3秒空间限制:32768K
  3. 本题知识点: 动态规划 递归
  4. 算法知识视频讲解
  5. 题目描述
  6. 请设计一种算法,解决著名的n皇后问题。这里的n皇后问题指在一个nxn的棋盘上放置n个棋子,使得每行每列和每条对角线上都只有一个棋子,求其摆放的方法数。
  7. 给定一个int n,请返回方法数,保证n小于等于10
  8. 测试样例:
  9. 1
  10. 返回:1

答案和思路,计算种类的:

  1. import java.util.*;
  2. public class Queens {
  3. // public static void main(String[] args) {
  4. // System.out.println(nQueens(2));
  5. // }
  6. public static int nQueens(int n) {
  7. // write code here
  8. int[] columns = new int[n];
  9. int[] res = new int[1];
  10. placeQueen(res, n, 0, columns);
  11. return res[0];
  12. }
  13. public static void placeQueen(int[] res, int n, int row, int[] columns) {
  14. if (n == row) {
  15. // row从0开始
  16. // 关键点:columns[i] = j表示第i行第j列放皇后
  17. res[0]++;
  18. } else {
  19. for (int j = 0; j < n; ++j) {
  20. // 看第几列可以放
  21. if (checkValid(row, j, columns)) {
  22. columns[row] = j; // 摆放皇后
  23. placeQueen(res, n, row + 1, columns);
  24. }
  25. }
  26. }
  27. }
  28. public static boolean checkValid(int row, int column, int[] columns) {
  29. for (int i = 0; i < row; ++i) {
  30. int haveColumn = columns[i];
  31. if (haveColumn == column) {
  32. return false;
  33. }
  34. if (Math.abs(haveColumn - column) == row - i) {
  35. return false;
  36. }
  37. }
  38. return true;
  39. }
  40. }

如果要打印的话,多加一个list就可以了。每次到了n的时候加list。

  1. import java.util.*;
  2. public class Main {
  3. public static void main(String[] args) {
  4. ArrayList<int[]> res = new ArrayList();
  5. int n = 4;
  6. res = nQueens(n);
  7. for (int[] a: res) {
  8. System.out.println(Arrays.toString(a));
  9. }
  10. }
  11. public static ArrayList<int[]> nQueens(int n) {
  12. // write code here
  13. int[] columns = new int[n];
  14. ArrayList<int[]> results = new ArrayList();
  15. placeQueen(n, 0, columns, results);
  16. return results;
  17. }
  18. public static void placeQueen(int n, int row, int[] columns,ArrayList<int[]> results) {
  19. if (n == row) {
  20. // row从0开始
  21. // 关键点:columns[i] = j表示第i行第j列放皇后
  22. results.add(columns.clone());
  23. } else {
  24. for (int j = 0; j < n; ++j) {
  25. // 看第几列可以放
  26. if (checkValid(row, j, columns)) {
  27. columns[row] = j; // 摆放皇后
  28. placeQueen(n, row + 1, columns, results);
  29. }
  30. }
  31. }
  32. }
  33. public static boolean checkValid(int row, int column, int[] columns) {
  34. for (int i = 0; i < row; ++i) {
  35. int haveColumn = columns[i];
  36. if (haveColumn == column) {
  37. return false;
  38. }
  39. if (Math.abs(haveColumn - column) == row - i) {
  40. return false;
  41. }
  42. }
  43. return true;
  44. }
  45. }

 10,------堆箱子

  1. 堆箱子
  2. 参与人数:146时间限制:3秒空间限制:32768K
  3. 本题知识点: 动态规划 递归
  4. 算法知识视频讲解
  5. 题目描述
  6. 有一堆箱子,每个箱子宽为wi,长为di,高为hi,现在需要将箱子都堆起来,而且为了使堆起来的箱子不到,上面的箱子的宽度和长度必须大于下面的箱子。请实现一个方法,求出能堆出的最高的高度,这里的高度即堆起来的所有箱子的高度之和。
  7. 给定三个int数组w,l,h,分别表示每个箱子宽、长和高,同时给定箱子的数目n。请返回能堆成的最高的高度。保证n小于等于500
  8. 测试样例:
  9. [1,1,1],[1,1,1],[1,1,1]
  10. 返回:1

答案和思路:因为有两个条件,那么可以把其中一个条件sort了。那么做dp的时候就只需要考虑那些满足第二个条件的得到的max。

  1. import java.util.*;
  2. public class Box {
  3. public int getHeight(int[] w, int[] l, int[] h, int n) {
  4. // write code here
  5. // sort by w
  6. for (int i = 0; i < n - 1; ++i) {
  7. for (int j = 1; j < n - i; ++j) {
  8. if (w[j] < w[j - 1]) {
  9. // swap
  10. swap(w, j, j - 1);
  11. swap(l, j, j - 1);
  12. swap(h, j, j - 1);
  13. }
  14. }
  15. }
  16. int result = 0;
  17. int[] dp = new int[n];
  18. for (int i = 0; i < n; ++i) {
  19. dp[i] = h[i];
  20. int preMax = 0;
  21. for (int j = 0; j < i; ++j) {
  22. if (w[j] < w[i] && l[j] < l[i]) {
  23. preMax = Math.max(preMax, dp[j]);
  24. }
  25. }
  26. dp[i] += preMax;
  27. if (dp[i] > result) {
  28. result = dp[i];
  29. }
  30. }
  31. return result;
  32. }
  33. public static void swap(int[] a, int i, int j) {
  34. int temp = a[i];
  35. a[i] = a[j];
  36. a[j] = temp;
  37. }
  38. }

 11,-------------由0,1, &, |, ^组成的布尔室。

 

第七章:数学和概率

补基础知识:1,素数指的是从2开始,只能被他和1整除的数。也叫作质素。2,合数指的是:除了能被1和它本身之外的自然数整除(不包括0)。

3,任何一个数都可以用质数(素数)的乘积来表示。证明:n==2的时候明显成立。那么假设n<k成立。k+1 = 一些数p1p2相乘。因为后面要讨论p1小于k。所以一种情况是本身就是素数,==k + 1乘1,这里没有小于k。除了这个的p1,p2也都是小于k那么,他们就可以分解成质数相乘。注意这些因子排序后,是唯一的。

4, 1和0不是质数也不是合数。

补充求素数最好的方式:

 

  1. public class Solution {
  2. public int countPrimes(int n) {
  3. boolean[] notPrime = new boolean[n]; // 因为是求小于n
  4. int count = 0;
  5. for (int i = 2; i < n; i++) {
  6. if (notPrime[i] == false) {
  7. count++;
  8. for (int j = 2; i * j < n; j++) {
  9. notPrime[i * j] = true;
  10. }
  11. }
  12. }
  13. return count;
  14. }
  15. }

 7.1,投篮球,玩法一:一次出手。玩法二:投三次,必须投中两次才算赢。假设投中概率是p

p1 = p;  p2 = 3 * p * p * (p - 1);  

算什么情况下选玩法一:p1 > p2.求得p < 0.5的时候。p > 0.5选第二种。但是p = 0, 1, 0.5两种都是一样的。

 

7.2,碰撞的蚂蚁,多边形上多个蚂蚁

  1. 碰撞的蚂蚁
  2. 参与人数:523时间限制:3秒空间限制:32768K
  3. 算法知识视频讲解
  4. 题目描述
  5. n个顶点的多边形上有n只蚂蚁,这些蚂蚁同时开始沿着多边形的边爬行,请求出这些蚂蚁相撞的概率。(这里的相撞是指存在任意两只蚂蚁会相撞)
  6. 给定一个int n(3<=n<=10000),代表n边形和n只蚂蚁,请返回一个double,为相撞的概率。
  7. 测试样例:
  8. 3
  9. 返回:0.75

答案:求不不可能碰撞的情况,就是同向。

  1. import java.util.*;
  2. public class Ants {
  3. public double antsCollision(int n) {
  4. // write code here
  5. return (1 - Math.pow(0.5, n - 1));
  6. }
  7. }

 

7.3,判断直线是否相交

  1. 判断直线相交
  2. 参与人数:490时间限制:3秒空间限制:32768K
  3. 算法知识视频讲解
  4. 题目描述
  5. 给定直角坐标系上的两条直线,确定这两条直线会不会相交。
  6. 线段以斜率和截距的形式给出,即double s1double s2double y1double y2,分别代表直线12的斜率(即s1,s2)和截距(即y1,y2),请返回一个bool,代表给定的两条直线是否相交。这里两直线重合也认为相交。
  7. 测试样例:
  8. 3.14,1,3.14,2
  9. 返回:false

答案:

  1. import java.util.*;
  2. public class CrossLine {
  3. public boolean checkCrossLine(double s1, double s2, double y1, double y2) {
  4. // write code here
  5. if (y1 == y2) {
  6. return true;
  7. }
  8. if (s1 == s2) {
  9. return false;
  10. }
  11. return true;
  12. }
  13. }

7.4,只使用加好来算乘法,除法,减法。

  1. 加法运算替代
  2. 参与人数:445时间限制:3秒空间限制:32768K
  3. 本题知识点: 编程基础
  4. 算法知识视频讲解
  5. 题目描述
  6. 请编写一个方法,实现整数的乘法、减法和除法运算(这里的除指整除)。只允许使用加号。
  7. 给定两个正整数int a,int b,同时给定一个int type代表运算的类型,1为求a b0为求a b,-1为求a b。请返回计算的结果,保证数据合法且结果一定在int范围内。
  8. 测试样例:
  9. 1,2,1
  10. 返回:2

答案:关键部分就是引入一个取反的函数negate

  1. import java.util.*;
  2. public class AddSubstitution {
  3. public int calc(int a, int b, int type) {
  4. int result = 0;
  5. if (type == 1) {
  6. result = multiply(a, b);
  7. } else if (type == 0) {
  8. result = divide(a, b);
  9. } else {
  10. result = minus(a, b);
  11. }
  12. return result;
  13. }
  14. private static int negate(int a) {
  15. int neg = 0;
  16. int d = a > 0 ? -1 : 1;
  17. for (int i = 0; i * i < a * a; i++) {
  18. neg += d;
  19. }
  20. return neg;
  21. }
  22. private static int minus(int a, int b) {
  23. int negB = negate(b);
  24. return a + negB;
  25. }
  26. private static int multiply(int a, int b) {
  27. int result = 0;
  28. for (int i = 0; i * i < a * a; ++i) {
  29. result += b;
  30. }
  31. if (a < 0 && b > 0 || a > 0 && b < 0) {
  32. result = negate(result);
  33. }
  34. return result;
  35. }
  36. private static int divide(int a, int b) {
  37. if (b > a) {
  38. return 0;
  39. }
  40. int result = 0;
  41. int a1 = a > 0 ? a : negate(a);
  42. int b1 = b > 0 ? b : negate(b);
  43. int sum = b1;
  44. while (sum <= a1) {
  45. result++;
  46. sum += b1;
  47. }
  48. if (a > 0 && b < 0 || a < 0 && b > 0) {
  49. result = negate(result);
  50. }
  51. return result;
  52. }
  53. }

 

7.5,平分的直线

  1. 平分的直线
  2. 参与人数:296时间限制:3秒空间限制:32768K
  3. 算法知识视频讲解
  4. 题目描述
  5. 在二维平面上,有两个正方形,请找出一条直线,能够将这两个正方形对半分。假定正方形的上下两条边与x轴平行。
  6. 给定两个vecotrAB,分别为两个正方形的四个顶点。请返回一个vector,代表所求的平分直线的斜率和截距,保证斜率存在。
  7. 测试样例:
  8. [(0,0),(0,1),(1,1),(1,0)],[(1,0),(1,1),(2,0),(2,1)]
  9. 返回:[0.00.5]

答案和知识点:注意要划分一个正方形的线,只要过中心就可以了。然后做题的时候注意一下。到底是哪个点减去哪个点得到中心。因为给的点顺序不一定相同。

  1. import java.util.*;
  2. /*
  3. public class Point {
  4. int x;
  5. int y;
  6. public Point(int x, int y) {
  7. this.x = x;
  8. this.y = y;
  9. }
  10. public Point() {
  11. this.x = 0;
  12. this.y = 0;
  13. }
  14. }*/
  15. public class Bipartition {
  16. public double[] getBipartition(Point[] a, Point[] b) {
  17. // write code here
  18. double[][] center = new double[2][2];
  19. center[0][0] = (a[1].x + a[0].x) / 2.0;
  20. center[0][1] = (a[3].y + a[0].y) / 2.0;
  21. center[1][0] = (b[1].x + b[0].x) / 2.0;
  22. center[1][1] = (b[3].y + b[0].y) / 2.0;
  23. double[] result = new double[2];
  24. result[0] = (center[1][1] - center[0][1]) * 1.0/ (center[1][0] - center[0][0]);
  25. result[1] = center[0][1] - result[0] * center[0][0];
  26. return result;
  27. }
  28. }

 7.6,过直线的点最多。

  1. 穿点最多的直线
  2. 参与人数:201时间限制:3秒空间限制:32768K
  3. 本题知识点: 高级结构 哈希 队列 链表 字符串 数组 编程基础 复杂度 穷举 模拟 分治 动态规划 贪心 递归 排序 查找
  4. 算法知识视频讲解
  5. 题目描述
  6. 在二维平面上,有一些点,请找出经过点数最多的那条线。
  7. 给定一个点集vector p和点集的大小n,请返回一个vector,代表经过点数最多的那条直线的斜率和截距。

答案和思路:暴力枚举。不过注意要单独写函数来求斜率,截距。单独写函数来判断有多少个点过函数。这里虽然没用到,但是记住double用==是不行的。

  1. import java.util.*;
  2. /*
  3. public class Point {
  4. int x;
  5. int y;
  6. public Point(int x, int y) {
  7. this.x = x;
  8. this.y = y;
  9. }
  10. public Point() {
  11. this.x = 0;
  12. this.y = 0;
  13. }
  14. }*/
  15. public class DenseLine {
  16. public double[] getLine(Point[] p, int n) {
  17. // write code here
  18. int max = 0;
  19. double[] result = new double[2];
  20. for (int i = 0; i < p.length; i++) {
  21. for (int j = i + 1; j < p.length; ++j) {
  22. double[] temp = getLine(p[i], p[j]);
  23. int num = getNum(temp, p);
  24. if (num > max) {
  25. result[0] = temp[0];
  26. result[1] = temp[1];
  27. }
  28. }
  29. }
  30. return result;
  31. }
  32. private static double[] getLine(Point a, Point b) {
  33. double[] result = new double[2];
  34. result[0] = (a.y - b.y) * 1.0 / (a.x - b.x);
  35. result[1] = a.y - result[0] * a.x;
  36. return result;
  37. }
  38. private static int getNum(double[] a, Point[] p) {
  39. int num = 0;
  40. for (int i = 0; i < p.length; ++i) {
  41. if (p[i].y == p[i].x * a[0] + a[1]) {
  42. num++;
  43. }
  44. }
  45. return num;
  46. }
  47. }

 7.7,找3,5,7因子组成的第K个数

  1. k个数
  2. 参与人数:423时间限制:3秒空间限制:32768K
  3. 算法知识视频讲解
  4. 题目描述
  5. 有一些数的素因子只有357,请设计一个算法,找出其中的第k个数。
  6. 给定一个数int k,请返回第k个数。保证k小于等于100
  7. 测试样例:
  8. 3
  9. 返回:7

答案:利用三个队列。首先队列一只放乘以3的。然后队列2只放乘以5的。队列7只放乘以7的。但是3里面出来的,要分别乘以3,5,7放到各个队列。5的要乘以5,7放到各个队列。这样就不会出现重复了。

  1. import java.util.*;
  2. public class KthNumber {
  3. public static int findKth(int k){
  4. int flag = 0;
  5. int num = 0;
  6. int tmp = 0;
  7. Queue<Integer> queue3 = new LinkedList();
  8. Queue<Integer> queue5 = new LinkedList();
  9. Queue<Integer> queue7 = new LinkedList();
  10. queue3.add(3);
  11. queue5.add(5);
  12. queue7.add(7);
  13. for(int i = 0; i < k; i++){
  14. int min = 0;
  15. if(queue3.peek() < queue5.peek()){
  16. if(queue3.peek() < queue7.peek()){
  17. flag = 3;
  18. }
  19. else{
  20. flag = 7;
  21. }
  22. }
  23. else{
  24. if(queue5.peek() < queue7.peek()){
  25. flag = 5;
  26. }
  27. else{
  28. flag = 7;
  29. }
  30. }
  31. if(flag == 3){
  32. tmp = queue3.poll();
  33. queue3.add(tmp * 3);
  34. queue5.add(tmp * 5);
  35. queue7.add(tmp * 7);
  36. }
  37. else if(flag == 5){
  38. tmp = queue5.poll();
  39. queue5.add(tmp * 5);
  40. queue7.add(tmp * 7);
  41. }
  42. else if(flag == 7){
  43. tmp = queue7.poll();
  44. queue7.add(tmp * 7);
  45. }
  46. flag = 0;
  47. }
  48. return tmp;
  49. }
  50. }

 

 

第六章:智力题(这里没有代码。所以就不解答了。)

 

第五章:位操作

基础知识:x^一串0 = x。 x^一串1 = ~x。

 获取x第i位:x &(1 << i);

置位,把x第i位变成1:x | (1 << i)。 把x第i位变成0: x  & (~( 1 << i))

清0 :清0第i位: x  & (~(1 << i))。 将最高位到第i位清0:x & ((1 << i) - 1)。 讲第i位至第0位清0:x & (~(1 << (i + 1) - 1));

更新:将x的第i位更新为v(v为0,或者1):x & (~(1 << i)) | (v << i)

5.1,二进制插入

  1. 二进制插入
  2. 参与人数:629时间限制:3秒空间限制:32768K
  3. 本题知识点: 编程基础
  4. 算法知识视频讲解
  5. 题目描述
  6. 有两个32位整数nm,请编写算法将m的二进制数位插入到n的二进制的第j到第i位,其中二进制的位数从低位数到高位且以0开始。
  7. 给定两个数int nint m,同时给定int jint i,意义如题所述,请返回操作后的数,保证n的第j到第i位均为零,且m的二进制位数小于等于i-j+1
  8. 测试样例:
  9. 10241926
  10. 返回:1100

答案和解析:注意看函数参数位置。这里把i,j搞反了。所以一直错。

把m插入n里面。那么从i到j这段位置把他清0.然后与m进行|。最后再通过移位对齐就可以了。

  1. import java.util.*;
  2. public class BinInsert {
  3. public int binInsert(int n, int m, int i, int j) {
  4. // write code here
  5. int allOnes = ~0;
  6. int left = allOnes << (j + 1);
  7. int right = (1 << i) - 1;
  8. int temp = n & (right | left);
  9. return temp | (m << i);
  10. }
  11. }

 5.2二进制数

  1. 二进制小数
  2. 参与人数:552时间限制:3秒空间限制:32768K
  3. 算法知识视频讲解
  4. 题目描述
  5. 有一个介于01之间的实数,类型为double,返回它的二进制表示。如果该数字无法精确地用32位以内的二进制表示,返回“Error”。
  6. 给定一个double num,表示01的实数,请返回一个string,代表该数的二进制表示或者“Error”。
  7. 测试样例:
  8. 0.625
  9. 返回:0.101

答:注意最后要检查是否是因为超出了32退出的,如果是的话要输出Error。

  1. import java.util.*;
  2. public class BinDecimal {
  3. public String printBin(double num) {
  4. // write code here
  5. StringBuffer sb = new StringBuffer();
  6. sb.append('0');
  7. sb.append('.');
  8. while (num != 0.0) {
  9. if (sb.length() >= 32) {
  10. break;
  11. }
  12. num = num * 2;
  13. if (num >= 1) {
  14. sb.append(1);
  15. num = num - 1;
  16. } else {
  17. sb.append(0);
  18. }
  19. }
  20. if (num != 0.0) {
  21. return "Error";
  22. }
  23. return new String(sb);
  24. }
  25. }

 5.3,最接近的两个数,1的个数相同。

  1. 最接近的数
  2. 参与人数:428时间限制:3秒空间限制:32768K
  3. 算法知识视频讲解
  4. 题目描述
  5. 有一个正整数,请找出其二进制表示中1的个数相同、且大小最接近的那两个数。(一个略大,一个略小)
  6. 给定正整数int x,请返回一个vector,代表所求的两个数(小的在前)。保证答案存在。
  7. 测试样例:
  8. 2
  9. 返回:[1,4]

答案:

  1. import java.util.*;
  2. public class CloseNumber {
  3. public int[] getCloseNumber(int x) {
  4. // write code here
  5. int[] res = new int[2];
  6. int num = getOnes(x);
  7. res[0] = x - 1;
  8. res[1] = x + 1;
  9. while (getOnes(res[0]) != num) {
  10. res[0]--;
  11. }
  12. while (getOnes(res[1]) != num) {
  13. res[1]++;
  14. }
  15. return res;
  16. }
  17. private static int getOnes(int x) {
  18. String str = Integer.toBinaryString(x);
  19. int num = 0;
  20. for (int i = 0; i < str.length(); i++) {
  21. if (str.charAt(i) == '1') {
  22. num++;
  23. }
  24. }
  25. return num;
  26. }
  27. }

5.4,解释n&(n-1) == 0含义

它用来判断n是否是2^n。

5.5,改变几位才能整数A转化成整数B。

  1. 整数转化
  2. 参与人数:613时间限制:3秒空间限制:32768K
  3. 算法知识视频讲解
  4. 题目描述
  5. 编写一个函数,确定需要改变几个位,才能将整数A转变成整数B
  6. 给定两个整数int Aint B。请返回需要改变的数位个数。
  7. 测试样例:
  8. 10,5
  9. 返回:4

答案:

  1. import java.util.*;
  2. public class Transform {
  3. public int calcCost(int A, int B) {
  4. // write code here
  5. int c = A ^ B;
  6. String str = Integer.toBinaryString(c);
  7. int res = 0;
  8. for (int i = 0; i < str.length(); ++i) {
  9. if (str.charAt(i) == '1') {
  10. res++;
  11. }
  12. }
  13. return res;
  14. }
  15. }

 5.6,奇偶位交换(二进制的奇偶位置交换)

  1. 奇偶位交换
  2. 参与人数:579时间限制:3秒空间限制:32768K
  3. 算法知识视频讲解
  4. 题目描述
  5. 请编写程序交换一个数的二进制的奇数位和偶数位。(使用越少的指令越好)
  6. 给定一个int x,请返回交换后的数int
  7. 测试样例:
  8. 10
  9. 返回:5

答案:先把偶数的提出来,往右走一位,然后把奇数位的提出来,往左走一位。

  1. import java.util.*;
  2. public class Exchange {
  3. public int exchangeOddEven(int x) {
  4. // write code here
  5. return ((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1);
  6. }
  7. }

 5.7,找出缺失的整数

  1. 找出缺失的整数
  2. 参与人数:286时间限制:3秒空间限制:32768K
  3. 算法知识视频讲解
  4. 题目描述
  5. 数组A包含了0n的所有整数,但其中缺失了一个。对于这个问题,我们设定限制,使得一次操作无法取得数组number里某个整数的完整内容。唯一的可用操作是询问数组中第i个元素的二进制的第j位(最低位为第0位),该操作的时间复杂度为常数,请设计算法,在O(n)的时间内找到这个数。
  6. 给定一个数组number,即所有剩下的数按从小到大排列的二进制各位的值,如A[0][1]表示剩下的第二个数二进制从低到高的第二位。同时给定一个int n,意义如题。请返回缺失的数。
  7. 测试样例:
  8. [[0],[0,1]]
  9. 返回:1

答案,思路太好了:最小位是0,1交替的。所以%2来判断是否缺失。注意的就是最小位放在素数的第一个位置。

  1. import java.util.*;
  2. public class Finder {
  3. public int findMissing(int[][] numbers, int n) {
  4. // write code here
  5. for (int i = 0; i < n; i++) {
  6. if (i % 2 != numbers[i][0]) {
  7. return i;
  8. }
  9. }
  10. return n;
  11. }
  12. }

 

 5.8,像素设定(染色二进制数组变成10进制)

  1. 像素设定
  2. 参与人数:312时间限制:3秒空间限制:32768K
  3. 算法知识视频讲解
  4. 题目描述
  5. 有一个单色屏幕储存在一维数组中,其中数组的每个元素代表连续的8位的像素的值,请实现一个函数,将第x到第y个像素涂上颜色(像素标号从零开始),并尝试尽量使用最快的办法。
  6. 给定表示屏幕的数组screen(数组中的每个元素代表连续的8个像素,且从左至右的像素分别对应元素的二进制的从低到高位),以及int x,int y,意义如题意所述,保证输入数据合法。请返回涂色后的新的屏幕数组。
  7. 测试样例:
  8. [0,0,0,0,0,0],0,47
  9. 返回:[255,255,255,255,255,255]

答案:注意只需要找出要处理的范围,不用去全部暴力。这里再次优化,只需要处理两个值,中间的都是255.但是要特判判断如果处理的只是一个值。那么染色要小心。

  1. import java.util.*;
  2. public class Render {
  3. public static void main(String[] args) {
  4. int[] a = {0, 0};
  5. System.out.println(Arrays.toString(renderPixel(a, 7, 7)));
  6. }
  7. public static int[] renderPixel(int[] screen, int x, int y) {
  8. // write code here
  9. if (null == screen || screen.length == 0) {
  10. return screen;
  11. }
  12. int length = screen.length;
  13. int start = x / 8 ;
  14. int end = y / 8 ;
  15. if (start == end) {
  16. int index1 = x % 8;
  17. int index2 = y % 8;
  18. String str = Integer.toBinaryString(screen[start]);
  19. char[] sb = new char[8];
  20. for (int i = 0; i < 8; ++i) {
  21. sb[i] = '0';
  22. }
  23. int index = 0;
  24. for (int i = str.length() - 1; i >= 0; i--) {
  25. sb[index++] = str.charAt(i);
  26. }
  27. for (int i = index1; i <= index2; i++) {
  28. sb[i] = '1';
  29. }
  30. int digit = 0;
  31. System.out.println(Arrays.toString(sb));
  32. for(int j = 0; j < 8; j++){
  33. digit = (int) (digit + (sb[j] - 48) * Math.pow(2, j));
  34. System.out.println(digit);
  35. }
  36. screen[start] = digit;
  37. return screen;
  38. }
  39. int index1 = x % 8;
  40. String str = Integer.toBinaryString(screen[start]);
  41. char[] sb = new char[8];
  42. for (int i = 0; i < 8; ++i) {
  43. sb[i] = '0';
  44. }
  45. int index = 0;
  46. for (int i = str.length() - 1; i >= 0; i--) {
  47. sb[index++] = str.charAt(i);
  48. }
  49. for (int i = index1; i < 8; i++) {
  50. sb[i] = '1';
  51. }
  52. int digit = 0;
  53. for(int j = 0; j < 8; j++){
  54. digit = (int) (digit + (sb[j] - 48) * Math.pow(2, j));
  55. }
  56. screen[start] = digit;
  57. int index2 = y % 8;
  58. String str2 = Integer.toBinaryString(screen[end]);
  59. char[] sb2 = new char[8];
  60. for (int i = 0; i < 8; ++i) {
  61. sb2[i] = '0';
  62. }
  63. index = 0;
  64. for (int i = str2.length() - 1; i >= 0; i--) {
  65. sb2[index++] = str2.charAt(i);
  66. }
  67. for (int i = 0; i <= index2; i++) {
  68. sb2[i] = '1';
  69. }
  70. digit = 0;
  71. System.out.println(Arrays.toString(sb2));
  72. for(int j = 0; j < 8; j++){
  73. digit = (int) (digit + (sb2[j] - 48) * Math.pow(2, j));
  74. }
  75. screen[end] = digit;
  76. for (int i = start + 1; i < end; i++) {
  77. screen[i] = 255;
  78. }
  79. return screen;
  80. }
  81. }

 

 

第四章:树与图

4.1,判断树是否平衡

 

  1. 实现一个函数,检查二叉树是否平衡,平衡的定义如下,对于树中的任意一个结点,其两颗子树的高度差不超过1
  2. 给定指向树根结点的指针TreeNode* root,请返回一个bool,代表这棵树是否平衡。

 

(1)答案和思路:首先利用高度来进行判断。

  1. import java.util.*;
  2. /*
  3. public class TreeNode {
  4. int val = 0;
  5. TreeNode left = null;
  6. TreeNode right = null;
  7. public TreeNode(int val) {
  8. this.val = val;
  9. }
  10. }*/
  11. public class Balance {
  12. public boolean isBalance(TreeNode root) {
  13. // write code here
  14. if (root == null) {
  15. return true;
  16. }
  17. if (Math.abs(height(root.left) - height(root.right)) > 1) {
  18. return false;
  19. } else {
  20. return isBalance(root.left) && isBalance(root.right);
  21. }
  22. }
  23. private static int height(TreeNode root) {
  24. if (root == null) {
  25. return 0;
  26. }
  27. return Math.max(height(root.left), height(root.right)) + 1;
  28. }
  29. }

优化:因为每一次都要不断地算树的高度。干脆直接在height函数里面算出他是否平衡。

  1. import java.util.*;
  2. /*
  3. public class TreeNode {
  4. int val = 0;
  5. TreeNode left = null;
  6. TreeNode right = null;
  7. public TreeNode(int val) {
  8. this.val = val;
  9. }
  10. }*/
  11. public class Balance {
  12. public boolean isBalance(TreeNode root) {
  13. // write code here
  14. if (root == null) {
  15. return true;
  16. }
  17. if (height(root) == -1) {
  18. return false;
  19. } else {
  20. return true;
  21. }
  22. }
  23. private static int height(TreeNode root) {
  24. if (root == null) {
  25. return 0;
  26. }
  27. int left = height(root.left);
  28. if (left == -1) {
  29. return -1;
  30. }
  31. int right = height(root.right);
  32. if (right == -1) {
  33. return -1;
  34. }
  35. if (Math.abs(left - right) > 1) {
  36. return -1;
  37. } else {
  38. return Math.max(left, right) + 1;
  39. }
  40. }
  41. }

顺便和下面的判断树是否是查找树一起做。

4.5,判断树是否是二叉查找树

 

 (1)答案和思路:引入最大值最小值来判断每一个节点是否满足这个要求,不满足,return false。记住递归中,一定要有终止条件。null就是终止条件。

  1. import java.util.*;
  2. /*
  3. public class TreeNode {
  4. int val = 0;
  5. TreeNode left = null;
  6. TreeNode right = null;
  7. public TreeNode(int val) {
  8. this.val = val;
  9. }
  10. }*/
  11. public class Checker {
  12. public boolean checkBST(TreeNode root) {
  13. // write code here
  14. if (root == null) {
  15. return true;
  16. }
  17. return checkBST(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
  18. }
  19. private static boolean checkBST(TreeNode root, int left, int right) {
  20. if (root == null) {
  21. return true;
  22. }
  23. if (root.val < left || root.val > right) {
  24. return false;
  25. }
  26. return checkBST(root.left, left, root.val) && checkBST(root.right,root.val, right);
  27. }
  28. }

 

4.2,有向路径检查。找图的两个节点是否存在路径

  1. 对于一个有向图,请实现一个算法,找出两点之间是否存在一条路径。
  2. 给定图中的两个结点的指针UndirectedGraphNode* a,UndirectedGraphNode* b(请不要在意数据类型,图是有向图),请返回一个bool,代表两点之间是否存在一条路径(abba)。

(1)答案和思路:注意的是这里是一个有向图。所以,要判断a到b还要判断b到a。  注意如何判断图的点是否出现过,可以用hashset来记录已经出现过的点。这是一个小技巧要记住了。然后就是BFS。用queue来做就可以了。

  1. import java.util.*;
  2. /*
  3. public class UndirectedGraphNode {
  4. int label = 0;
  5. UndirectedGraphNode left = null;
  6. UndirectedGraphNode right = null;
  7. ArrayList<UndirectedGraphNode> neighbors = new ArrayList<UndirectedGraphNode>();
  8. public UndirectedGraphNode(int label) {
  9. this.label = label;
  10. }
  11. }*/
  12. public class Path {
  13. public boolean checkPath(UndirectedGraphNode a, UndirectedGraphNode b) {
  14. return checkPath2(a, b) || checkPath2(b, a);
  15. }
  16. public static boolean checkPath2(UndirectedGraphNode a, UndirectedGraphNode b) {
  17. // write code here
  18. if ( a == b) {
  19. return true;
  20. }
  21. Queue<UndirectedGraphNode> queue = new LinkedList();
  22. HashSet hash = new HashSet();
  23. hash.add(a);
  24. queue.add(a);
  25. while (!queue.isEmpty()) {
  26. UndirectedGraphNode top = queue.poll();
  27. for (UndirectedGraphNode g : top.neighbors) {
  28. if (g == b) {
  29. return true;
  30. }
  31. if (!hash.contains(g)) {
  32. queue.add(g);
  33. hash.add(g);
  34. }
  35. }
  36. }
  37. return false;
  38. }
  39. }

 4.3,求建立BST树的高度(附上如何建立一棵BST树)

  1. 高度最小的BST
  2. 参与人数:715时间限制:3秒空间限制:32768K
  3. 本题知识点: 高级结构
  4. 算法知识视频讲解
  5. 题目描述
  6. 对于一个元素各不相同且按升序排列的有序序列,请编写一个算法,创建一棵高度最小的二叉查找树。
  7. 给定一个有序序列int[] vals,请返回创建的二叉查找树的高度。

 答案:求高度的答案。利用2^height - 1 = nums; height = nums + 1的log2为低。利用好Math.ceil取上整。

  1. import java.util.*;
  2. public class MinimalBST {
  3. public int buildMinimalBST(int[] vals) {
  4. if (vals == null || vals.length == 0) {
  5. return 0;
  6. }
  7. int length = vals.length;
  8. return (int)Math.ceil(Math.log(length + 1) / Math.log(2));
  9. }
  10. }

这里是真正建立了一棵树,然后再通过BST树来求高度。

  1. import java.util.*;
  2. class TreeNode {
  3. int val;
  4. TreeNode left;
  5. TreeNode right;
  6. TreeNode(int v) {
  7. val = v;
  8. left = null;
  9. right = null;
  10. }
  11. }
  12. public class MinimalBST {
  13. public int buildMinimalBST(int[] vals) {
  14. if (vals == null || vals.length == 0) {
  15. return 0;
  16. }
  17. int length = vals.length;
  18. TreeNode root = buildMinimalBST(vals, 0, length - 1);
  19. return height(root);
  20. }
  21. public static TreeNode buildMinimalBST(int[] vals, int start, int end) {
  22. if (end < start) {
  23. return null;
  24. }
  25. int mid = (start + end) / 2;
  26. TreeNode n = new TreeNode(vals[mid]);
  27. n.left = buildMinimalBST(vals, start, mid - 1);
  28. n.right = buildMinimalBST(vals, mid + 1, end);
  29. return n;
  30. }
  31. private static int height(TreeNode root) {
  32. if (root == null) {
  33. return 0;
  34. }
  35. return Math.max(height(root.left), height(root.right)) + 1;
  36. }
  37. }

 4.4,建立树在某一层的链表。

  1. 输出单层结点
  2. 参与人数:626时间限制:3秒空间限制:32768K
  3. 本题知识点:
  4. 算法知识视频讲解
  5. 题目描述
  6. 对于一棵二叉树,请设计一个算法,创建含有某一深度上所有结点的链表。
  7. 给定二叉树的根结点指针TreeNode* root,以及链表上结点的深度,请返回一个链表ListNode,代表该深度上所有结点的值,请按树上从左往右的顺序链接,保证深度不超过树的高度,树上结点的值为非负整数且不超过100000

答案:注意看链表存的是什么,是树节点,还是他的值。另外一个这里只需要建立一层。而另一种需求是所有层都建立。没有Bug-free:没有特判深度是1.

  1. import java.util.*;
  2. /*
  3. public class ListNode {
  4. int val;
  5. ListNode next = null;
  6. ListNode(int val) {
  7. this.val = val;
  8. }
  9. }*/
  10. /*
  11. public class TreeNode {
  12. int val = 0;
  13. TreeNode left = null;
  14. TreeNode right = null;
  15. public TreeNode(int val) {
  16. this.val = val;
  17. }
  18. }*/
  19. public class TreeLevel {
  20. public ListNode getTreeLevel(TreeNode root, int dep) {
  21. // write code here
  22. ListNode head = new ListNode(0);
  23. if (root == null) {
  24. return head;
  25. }
  26. Queue<TreeNode> queue = new LinkedList();
  27. queue.add(root);
  28. if (dep == 1) {
  29. return new ListNode(root.val);
  30. }
  31. int height = 1;
  32. ListNode cur = head;
  33. while (queue.size() != 0) {
  34. int size = queue.size();
  35. if (height == dep - 1) {
  36. for (int i = 0; i < size; i++) {
  37. TreeNode node = queue.poll();
  38. if (node.left != null) {
  39. cur.next = new ListNode(node.left.val);
  40. cur = cur.next;
  41. }
  42. if (node.right != null) {
  43. cur.next = new ListNode(node.right.val);
  44. cur = cur.next;
  45. }
  46. }
  47. break;
  48. }
  49. for (int i = 0; i < size; ++i) {
  50. TreeNode n = queue.poll();
  51. if (n.left != null) {
  52. queue.add(n.left);
  53. }
  54. if (n.right != null) {
  55. queue.add(n.right);
  56. }
  57. }
  58. height++;
  59. }
  60. return head.next;
  61. }
  62. }

4.6,找中序后继结点

  1. 寻找下一个结点
  2. 参与人数:595时间限制:3秒空间限制:32768K
  3. 本题知识点:
  4. 算法知识视频讲解
  5. 题目描述
  6. 请设计一个算法,寻找二叉树中指定结点的下一个结点(即中序遍历的后继)。
  7. 给定树的根结点指针TreeNode* root和结点的值int p,请返回值为p的结点的后继结点的值。保证结点的值大于等于零小于等于100000且没有重复值,若不存在后继返回-1

答案和思路:记住flag只有是全局变量的时候才会一直被保存。

  1. import java.util.*;
  2. /*
  3. public class TreeNode {
  4. int val = 0;
  5. TreeNode left = null;
  6. TreeNode right = null;
  7. public TreeNode(int val) {
  8. this.val = val;
  9. }
  10. }*/
  11. public class Successor {
  12. static int result = -1;
  13. static boolean flag = false;
  14. public int findSucc(TreeNode root, int p) {
  15. // write code here
  16. if (root == null) {
  17. return -1;
  18. }
  19. inOrder(root, p);
  20. return result;
  21. }
  22. private static void inOrder(TreeNode root, int p) {
  23. if (root == null) {
  24. return;
  25. }
  26. inOrder(root.left, p);
  27. if (flag) {
  28. result = root.val;
  29. flag = false;
  30. }
  31. if (root.val == p) {
  32. flag = true;
  33. }
  34. inOrder(root.right, p);
  35. }
  36. }

 4.7,找最近公共祖先(LowestCommonAncestor, LCA)

  1. 给定一棵二叉树,找到两个节点的最近公共父节点(LCA)。
  2. 最近公共祖先是两个节点的公共的祖先节点且具有最大深度。

答案和解析:利用先遇到谁。首先如果root与其中一个相等,或者==null,那么肯定返回root。开始左右递归。left记录左边的先遇到的值。right记录右边先遇到的值。如果一直没有遇到那么为null。当两边都遇到了,那么祖先是上一层。如果只有一边不是null。那么说明遇到他就已经退出了。他就是祖先。

  1. /**
  2. * Definition of TreeNode:
  3. * public class TreeNode {
  4. * public int val;
  5. * public TreeNode left, right;
  6. * public TreeNode(int val) {
  7. * this.val = val;
  8. * this.left = this.right = null;
  9. * }
  10. * }
  11. */
  12. public class Solution {
  13. /**
  14. * @param root: The root of the binary search tree.
  15. * @param A and B: two nodes in a Binary.
  16. * @return: Return the least common ancestor(LCA) of the two nodes.
  17. */
  18. // public TreeNode lowestCommonAncestor(TreeNode root, TreeNode A, TreeNode B) {
  19. // // write your code here
  20. // }
  21. public TreeNode lowestCommonAncestor(TreeNode root, TreeNode A, TreeNode B) {
  22. if (root == null || root == A || root == B) {
  23. return root;
  24. }
  25. TreeNode left = lowestCommonAncestor(root.left, A, B);
  26. TreeNode right = lowestCommonAncestor(root.right, A, B);
  27. if (left != null && right != null) {
  28. return root;
  29. } else if (left != null) {
  30. return left;
  31. } else {
  32. return right;
  33. }
  34. }
  35. }

这题,牛客网靠的是满二叉树的LCA:

答案:这题非常简单。只要a,b不等就一直往上退。谁大就让谁变成他父亲,即除以2。一直到它们相等,一直会相遇的。

  1. import java.util.*;
  2. public class LCA {
  3. public int getLCA(int a, int b) {
  4. // write code here
  5. while (a != b) {
  6. if (a > b) {
  7. a = a / 2;
  8. } else {
  9. b = b / 2;
  10. }
  11. }
  12. return a;
  13. }
  14. }

 4.8,---找是否是子树

  1. 子树
  2. 描述
  3. 笔记
  4. 数据
  5. 评测
  6. 有两个不同大小的二进制树: T1 有上百万的节点; T2 有好几百的节点。请设计一种算法,判定 T2 是否为 T1的子树。
  7. 您在真实的面试中是否遇到过这个题? Yes
  8. 注意事项
  9. T1 中存在从节点 n 开始的子树与 T2 相同,我们称 T2 T1 的子树。也就是说,如果在 T1 节点 n 处将树砍断,砍断的部分将与 T2 完全相同。
  10. 样例
  11. 下面的例子中 T2 T1 的子树:
  12. 1 3
  13. / \ /
  14. T1 = 2 3 T2 = 4
  15. /
  16. 4
  17. 下面的例子中 T2 不是 T1 的子树:
  18. 1 3
  19. / \ \
  20. T1 = 2 3 T2 = 4
  21. /
  22. 4

答:这里注意子树指的是从那里一开始一直到最后都是一幕一样的。叶节点也是一样的。所以,他们必须走到最后。思路的话:就是写一个判断两棵树是否完全相同的函数。然后在大树离开时找那些val==小树根val的点,然后判断他是否构成了子树。

  1. /**
  2. * Definition of TreeNode:
  3. * public class TreeNode {
  4. * public int val;
  5. * public TreeNode left, right;
  6. * public TreeNode(int val) {
  7. * this.val = val;
  8. * this.left = this.right = null;
  9. * }
  10. * }
  11. */
  12. public class Solution {
  13. /**
  14. * @param T1, T2: The roots of binary tree.
  15. * @return: True if T2 is a subtree of T1, or false.
  16. */
  17. public boolean isSubtree(TreeNode T1, TreeNode T2) {
  18. // write your code here
  19. if (T2 == null) {
  20. return true;
  21. }
  22. if (T1 == null) {
  23. return false;
  24. }
  25. if (T1.val == T2.val) {
  26. if (isSame(T1, T2)) {
  27. return true;
  28. }
  29. }
  30. return isSubtree(T1.left, T2) || isSubtree(T1.right, T2);
  31. }
  32. private static boolean isSame(TreeNode t1, TreeNode t2) {
  33. if (t1 == null && t2 == null) {
  34. return true;
  35. }
  36. if (t1 == null || t2 == null) {
  37. return false;
  38. }
  39. if (t1.val != t2.val) {
  40. return false;
  41. }
  42. return isSame(t1.left, t2.left) && isSame(t1.right, t2.right);
  43. }
  44. }

4.9,找二叉树的路径和

  1. 二叉树中和为某一值的路径
  2. 参与人数:2478时间限制:1秒空间限制:32768K
  3. 算法知识视频讲解
  4. 题目描述
  5. 输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。

升级:可以从任意节点开始,然后任意节点结束。那么接替的思路就是,把每一个节点当做最后一个节点。卡一个path[height]的路径。这里我们知道每一层就会放到path[level]上。关键点:找到了sum不要停,继续往上走。因为可能有负数。

  1. public static void findSum(TreeNode node, int sum, int[] path, int level) {
  2. if (node == null) {
  3. return;
  4. }
  5. /* Insert current node into path */
  6. path[level] = node.data;
  7. int t = 0;
  8. for (int i = level; i >= 0; i--){
  9. t += path[i];
  10. if (t == sum) {
  11. print(path, i, level);
  12. }
  13. }
  14. findSum(node.left, sum, path, level + 1);
  15. findSum(node.right, sum, path, level + 1);
  16. /* Remove current node from path. Not strictly necessary, since we would
  17. * ignore this value, but it's good practice.
  18. */
  19. path[level] = Integer.MIN_VALUE;
  20. }
  21. public static int depth(TreeNode node) {
  22. if (node == null) {
  23. return 0;
  24. } else {
  25. return 1 + Math.max(depth(node.left), depth(node.right));
  26. }
  27. }
  28. public static void findSum(TreeNode node, int sum) {
  29. int depth = depth(node);
  30. int[] path = new int[depth];
  31. findSum(node, sum, path, 0);
  32. }
  33. private static void print(int[] path, int start, int end) {
  34. for (int i = start; i <= end; i++) {
  35. System.out.print(path[i] + " ");
  36. }
  37. System.out.println();
  38. }

 

 

 

第三章:栈与队列

3.1一个数组设计三个栈。一种是划分为3分。一种是动态的划分。数组是一个循环数组。

3.2,包含O(1)min操作的栈的实现。

 (1)答案和思路:再用一个stack来存就可以了。注意问题就是区分好pop和top。不要混淆了。

  1. class MinStack {
  2. Stack<Integer> stack = new Stack();
  3. Stack<Integer> minStack = new Stack();
  4. public void push(int x) {
  5. stack.push(x);
  6. if (minStack.size() == 0 || x <= minStack.peek()) {
  7. minStack.push(x);
  8. } else {
  9. minStack.push(minStack.peek());
  10. }
  11. }
  12. public void pop() {
  13. minStack.pop();
  14. stack.pop();
  15. }
  16. public int top() {
  17. return stack.peek();
  18. }
  19. public int getMin() {
  20. return minStack.peek();
  21. }
  22. }

 3.3,集合栈

  1. 请实现一种数据结构SetOfStacks,由多个栈组成,其中每个栈的大小为size,当前一个栈填满时,新建一个栈。该数据结构应支持与普通栈相同的pushpop操作。
  2. 给定一个操作序列int[][] ope(C++为vector<vector<int>>),每个操作的第一个数代表操作类型,若为1,则为push操作,后一个数为应push的数字;若为2,则为pop操作,后一个数无意义。请返回一个int[][](C++为vector<vector<int>>),为完成所有操作后的SetOfStacks,顺序应为从下到上,默认初始的SetOfStacks为空。保证数据合法。

(1)答案和思路:注意一下,满了要新建,pop空了要删除就可以了。

  1. import java.util.*;
  2. public class SetOfStacks {
  3. public ArrayList<ArrayList<Integer>> setOfStacks(int[][] ope, int size) {
  4. // write code here
  5. ArrayList<ArrayList<Integer>> result = new ArrayList();
  6. ArrayList<Integer> stack = new ArrayList();
  7. result.add(stack);
  8. if (ope == null || ope.length == 0 || size <= 0) {
  9. return null;
  10. }
  11. for (int i = 0; i < ope.length; i++) {
  12. if (ope[i][0] == 1) {
  13. // push
  14. if (result.get(result.size() - 1).size() == size) {
  15. ArrayList<Integer> temp = new ArrayList();
  16. temp.add(ope[i][1]);
  17. result.add(temp);
  18. } else {
  19. result.get(result.size() - 1).add(ope[i][1]);
  20. }
  21. } else {
  22. result.get(result.size() - 1).remove(result.get(result.size() - 1).size() - 1);
  23. if (result.get(result.size() - 1).size() == 0) {
  24. result.remove(result.size() - 1);
  25. }
  26. }
  27. }
  28. return result;
  29. }
  30. }

 

 3.4,汉诺塔(暂时没看)

 

 

3.5,两个栈实现一个队列

  1. import java.util.Stack;
  2. public class Solution {
  3. Stack<Integer> stack1 = new Stack<Integer>();
  4. Stack<Integer> stack2 = new Stack<Integer>();
  5. public void push(int node) {
  6. stack1.push(node);
  7. }
  8. public int pop() {
  9. if (stack2.isEmpty()) {
  10. while(!stack1.isEmpty()) {
  11. stack2.push(stack1.pop());
  12. }
  13. }
  14. return stack2.pop();
  15. }
  16. }

3.6,双栈排序

  1. 请编写一个程序,按升序对栈进行排序(即最大元素位于栈顶),要求最多只能使用一个额外的栈存放临时数据,但不得将元素复制到别的数据结构中。
  2. 给定一个int[] numbers(C++中为vector&ltint>),其中第一个元素为栈顶,请返回排序后的栈。请注意这是一个栈,意味着排序过程中你只能访问到第一个元素。

对应的牛客网的题目答案:

  1. import java.util.*;
  2. public class TwoStacks {
  3. public ArrayList<Integer> twoStacksSort(int[] numbers) {
  4. // write code here
  5. ArrayList<Integer> result = new ArrayList();
  6. if (numbers == null || numbers.length == 0) {
  7. return result;
  8. }
  9. for (int i = 0; i < numbers.length; i++) {
  10. if (result.size() == 0) {
  11. result.add(numbers[i]);
  12. continue;
  13. }
  14. boolean flag = true;
  15. for (int j = 0; j < result.size(); j++) {
  16. if (numbers[i] > result.get(j)) {
  17. result.add(j, numbers[i]);
  18. flag = false;
  19. break;
  20. }
  21. }
  22. if (flag) {
  23. result.add(numbers[i]);
  24. }
  25. }
  26. return result;
  27. }
  28. }

(1)答案和思路:每次取出来的s1的栈顶元素,然后把s2的那些比他大的放到s1上。知道它可以插入。

  1. import java.util.Stack;
  2. public class Main {
  3. public static Stack<Integer> sort(Stack<Integer> s) {
  4. Stack<Integer> s2 = new Stack();
  5. while (!s.isEmpty()) {
  6. int tmp = s.pop();
  7. while (!s2.isEmpty() && s2.peek() > tmp) {
  8. s.push(s2.pop());
  9. }
  10. s2.push(tmp);
  11. }
  12. return s2;
  13. }
  14. }

 3.7,猫狗收容所(先收养老的原则)

  1. 题目描述
  2. 有家动物收容所只收留猫和狗,但有特殊的收养规则,收养人有两种收养方式,第一种为直接收养所有动物中最早进入收容所的,第二种为选择收养的动物类型(猫或狗),并收养该种动物中最早进入收容所的。
  3. 给定一个操作序列int[][2] ope(C++中为vector<vector<int>>)代表所有事件。若第一个元素为1,则代表有动物进入收容所,第二个元素为动物的编号,正数代表狗,负数代表猫;若第一个元素为2,则代表有人收养动物,第二个元素若为0,则采取第一种收养方式,若为1,则指定收养狗,若为-1则指定收养猫。请按顺序返回收养的序列。若出现不合法的操作,即没有可以符合领养要求的动物,则将这次领养操作忽略。
  4. 测试样例:
  5. [[1,1],[1,-1],[2,0],[2,-1]]
  6. 返回:[1,-1]

(1)答案和思路:分别用猫狗两个队列,那么如何区分谁先进去呢。给每一个都加一次time标志。所以队列里面存的是Animal class(有order,有time)。

注意的就是要一直判空,因为有非法操作。

  1. import java.util.ArrayList;
  2. import java.util.LinkedList;
  3. import java.util.Queue;
  4. class Animal {
  5. int order;
  6. int time;
  7. Animal (int o, int t) {
  8. order = o;
  9. time = t;
  10. }
  11. }
  12. public class CatDogAsylum {
  13. public static void main(String[] args) {
  14. int[][] a = {{1,-3},{1,-6},{1,10},{1,3},{2,0},{1,19},{2,-1},{1,-81},{1,36},{2,0},{2,1},{1,66},{2,0},{1,-13},{2,0},{2,-1},{2,0},{1,29},{2,1},{2,1},{2,1},{1,56},{1,-99},{2,-1},{2,-1},{1,79},{1,-25},{1,-6},{1,63},{1,48},{1,-40},{1,56},{2,1},{1,28},{1,78},{1,20},{1,18},{1,20},{1,-92},{1,87},{2,0},{1,34},{2,-1},{1,96},{1,38},{2,0},{2,-1},{1,17},{1,13},{1,3},{1,-26},{2,0},{2,0},{2,-1},{2,1},{2,0},{1,-78},{1,57},{1,71},{1,-11},{2,-1},{1,-28},{1,-28},{1,-87},{1,-86},{1,-9},{1,50},{2,1},{2,0},{1,65},{1,-98},{1,-54},{2,0},{2,-1},{1,84},{1,-72},{1,-42},{1,77},{1,-61},{1,-61},{1,-11},{1,94},{2,1},{1,93},{2,-1},{2,-1},{1,43},{2,-1},{1,-72},{2,-1},{1,-31},{1,-41},{1,-85},{1,-2},{2,0},{1,94},{1,80},{1,-86},{1,-83},{1,-20},{1,49},{1,-47},{1,46},{1,34},{2,1},{2,0},{1,-41},{2,1},{2,-1},{1,-44},{1,100},{1,-85},{1,-25},{1,-8},{1,-69},{1,13},{1,82},{2,1},{1,-41},{1,-44},{1,22},{1,-72},{1,-16},{1,-11},{1,65},{1,-66},{1,25},{1,-31},{1,-63},{2,1},{1,86},{1,2},{1,6},{1,-42},{1,-9},{1,76},{1,54},{2,0},{2,1}};
  15. System.out.println(asylum(a));
  16. }
  17. public static ArrayList<Integer> asylum(int[][] ope) {
  18. // write code here
  19. ArrayList<Integer> result = new ArrayList();
  20. if (ope == null || ope.length == 0) {
  21. return result;
  22. }
  23. int time = 0;
  24. Queue<Animal> qDog = new LinkedList();
  25. Queue<Animal> qCat = new LinkedList();
  26. for (int i = 0; i < ope.length; i++) {
  27. if (ope[i][0] == 1) {
  28. ++time;
  29. if (ope[i][1] > 0) {
  30. qDog.add(new Animal(ope[i][1], time));
  31. } else if (ope[i][1] < 0){
  32. qCat.add(new Animal(ope[i][1], time));
  33. }
  34. } else if (ope[i][0] == 2) {
  35. if (ope[i][1] == 0) {
  36. if (qCat.size() == 0 || qDog.size() != 0 && qDog.peek().time < qCat.peek().time) {
  37. result.add(qDog.poll().order);
  38. } else if (qDog.size() == 0 || qCat.size() != 0 && qCat.peek().time < qDog.peek().time) {
  39. result.add(qCat.poll().order);
  40. }
  41. } else if (ope[i][1] == 1) {
  42. if (qDog.size() != 0) {
  43. result.add(qDog.poll().order);
  44. }
  45. } else if (ope[i][1] == -1) {
  46. if (qCat.size() != 0) {
  47. result.add(qCat.poll().order);
  48. }
  49. }
  50. }
  51. }
  52. return result;
  53. }
  54. }

 

 

 

第二章:链表

2.1,删除链表中重复的元素。(让链表的每一个元素都只出现一次)

(1)答案和思路:一种是利用hash来看是否出现删除。还有一种是要求不能使用缓冲区,那么就用双指针来删除。

  1. import java.util.HashSet;
  2. class ListNode {
  3. int val;
  4. ListNode next;
  5. ListNode() {
  6. }
  7. }
  8. public class Main {
  9. //用hash
  10. public static void deleteDups(ListNode n) {
  11. HashSet hash = new HashSet();
  12. ListNode preHead = new ListNode();
  13. preHead.next = n;
  14. while (n != null) {
  15. if (hash.contains(n.val)) {
  16. preHead.next = n.next;
  17. } else {
  18. hash.add(n.val);
  19. preHead = n;
  20. }
  21. n = n.next;
  22. }
  23. }
  24. //不能够临时缓冲区
  25. public static void deleteDups2(ListNode head) {
  26. if (head == null) {
  27. return;
  28. }
  29. ListNode cur = head;
  30. ListNode fast = head;
  31. while (cur != null) {
  32. fast = cur;
  33. while (fast.next != null) {
  34. if (fast.next.val == cur.val) {
  35. fast.next = fast.next.next;
  36. } else {
  37. fast = fast.next;
  38. }
  39. }
  40. }
  41. cur = cur.next;
  42. }
  43. }

 2.2,输入一个链表,输出该链表中倒数第k个结点。

 (1)答案和思路:记得要判断k==0.输出null。不然会报错。

  1. /*
  2. public class ListNode {
  3. int val;
  4. ListNode next = null;
  5. ListNode(int val) {
  6. this.val = val;
  7. }
  8. }*/
  9. public class Solution {
  10. public ListNode FindKthToTail(ListNode head,int k) {
  11. if (head == null || k <= 0) {
  12. return null;
  13. }
  14. // Error :如果K比length大怎么办要判断
  15. // Error : k <= 0 也要特殊判断
  16. ListNode fast = head;
  17. for (int i = 0; i < k - 1; i++) {
  18. fast = fast.next;
  19. if (fast == null) {
  20. return fast;
  21. }
  22. }
  23. while (fast.next != null) {
  24. head = head.next;
  25. fast = fast.next;
  26. }
  27. return head;
  28. }
  29. }

 2.3,删除链表中的某一个结点

  1. 实现一个算法,删除单向链表中间的某个结点,假定你只能访问该结点。
  2. 给定带删除的节点,请执行删除操作,若该节点为尾节点,返回false,否则返回true

(1)答案和思路:注意可以返回boolean表示是否删除成功,如果是尾结点。设置为:false;

  1. public class Remove {
  2. public boolean removeNode(ListNode pNode) {
  3. // write code here
  4. if (pNode == null || pNode.next == null) {
  5. return false;
  6. }
  7. pNode.val = pNode.next.val;
  8. pNode.next = pNode.next.next;
  9. return true;
  10. }
  11. }

 2.4,链表分割(小于x的在一边。大于等于x的又在一边)

  1. 编写代码,以给定值x为基准将链表分割成两部分,所有小于x的结点排在大于或等于x的结点之前
  2. 给定一个链表的头指针 ListNode* pHead,请返回重新排列后的链表的头指针。注意:分割以后保持原来的数据顺序不变。

(1)答案:开两个链表来存一下。注意不要忘记next。然后无论是small还是big的头都是个虚头。这样更方便。

  1. import java.util.*;
  2. /*
  3. public class ListNode {
  4. int val;
  5. ListNode next = null;
  6. ListNode(int val) {
  7. this.val = val;
  8. }
  9. }*/
  10. public class Partition {
  11. public ListNode partition(ListNode pHead, int x) {
  12. // write code here
  13. ListNode small = new ListNode(0);
  14. ListNode big = new ListNode(0);
  15. ListNode tempSmall = small;
  16. ListNode tempBig = big;
  17. while (pHead != null) {
  18. if (pHead.val < x) {
  19. tempSmall.next = new ListNode(pHead.val);
  20. tempSmall = tempSmall.next;
  21. } else {
  22. tempBig.next = new ListNode(pHead.val);
  23. tempBig = tempBig.next;
  24. }
  25. //Error: 没有next
  26. pHead = pHead.next;
  27. }
  28. tempSmall.next = big.next;
  29. return small.next;
  30. }
  31. }

 2.5,链表相加A+B(链表存的是数位)

  1. 有两个用链表表示的整数,每个结点包含一个数位。这些数位是反向存放的,也就是个位排在链表的首部。编写函数对这两个整数求和,并用链表形式返回结果。
  2. 给定两个链表ListNode* AListNode* B,请返回A+B的结果(ListNode*)。
  3. 测试样例:
  4. {1,2,3},{3,2,1}
  5. 返回:{4,4,4}

(1)思路和答案:注意最后如果digit还有值要继续新建。

  1. import java.util.*;
  2. /*
  3. public class ListNode {
  4. int val;
  5. ListNode next = null;
  6. ListNode(int val) {
  7. this.val = val;
  8. }
  9. }*/
  10. public class Plus {
  11. public ListNode plusAB(ListNode a, ListNode b) {
  12. // write code here
  13. if (a == null) {
  14. return b;
  15. }
  16. if (b == null) {
  17. return a;
  18. }
  19. ListNode preHead = new ListNode(0);
  20. ListNode cur = preHead;
  21. int sum = 0;
  22. int digit = 0;
  23. while (a != null || b != null) {
  24. if (a != null && b != null) {
  25. sum = a.val + b.val + digit;
  26. digit = sum / 10;
  27. sum = sum - digit * 10;
  28. cur.next = new ListNode(sum);
  29. cur = cur.next;
  30. a = a.next;
  31. b = b.next;
  32. } else if (a != null) {
  33. sum = a.val + digit;
  34. digit = sum / 10;
  35. sum = sum - digit * 10;
  36. cur.next = new ListNode(sum);
  37. cur = cur.next;
  38. a = a.next;
  39. } else {
  40. sum = b.val + digit;
  41. digit = sum / 10;
  42. sum = sum - digit * 10;
  43. cur.next = new ListNode(sum);
  44. cur = cur.next;
  45. b = b.next;
  46. }
  47. }
  48. //Error: 别忘记如果最后digit还有值的话要判断一下。
  49. if (digit != 0) {
  50. cur.next = new ListNode(digit);
  51. }
  52. return preHead.next;
  53. }
  54. }

 2.6,找链表的环的起点

(1)答案和思路:注意的地方就是判断有没有环的时候,要记得写fast == slow break。

  1. /**
  2. * Definition for singly-linked list.
  3. * class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) {
  7. * val = x;
  8. * next = null;
  9. * }
  10. * }
  11. */
  12. public class Solution {
  13. public ListNode detectCycle(ListNode head) {
  14. if (null == head || head.next == null) {
  15. return null;
  16. }
  17. ListNode fast = head;
  18. ListNode slow = head;
  19. while (fast != null && fast.next != null) {
  20. fast = fast.next.next;
  21. slow = slow.next;
  22. if (fast == slow) {
  23. break;
  24. }
  25. }
  26. if (fast != slow) {
  27. return null;
  28. }
  29. slow = head;
  30. while (slow != fast) {
  31. slow = slow.next;
  32. fast = fast.next;
  33. }
  34. return fast;
  35. }
  36. }

 2.7,判断链表是否是回文

  1. 请编写一个函数,检查链表是否为回文。
  2. 给定一个链表ListNode* pHead,请返回一个bool,代表链表是否为回文。
  3. 测试样例:
  4. {1,2,3,2,1}
  5. 返回:true
  6. {1,2,3,2,3}
  7. 返回:false

(1)答案和思路:千万不能试图翻转整个链表来比较。因为那样链表完全被改变了。

然后利用的是翻转后半段链表来比较。注意,fast.next。不要少了一个next。

  1. import java.util.*;
  2. /*
  3. public class ListNode {
  4. int val;
  5. ListNode next = null;
  6. ListNode(int val) {
  7. this.val = val;
  8. }
  9. }*/
  10. public class Palindrome {
  11. public boolean isPalindrome(ListNode pHead) {
  12. // write code here
  13. if (pHead == null || pHead.next == null) {
  14. return true;
  15. }
  16. ListNode slow = pHead;
  17. ListNode fast = pHead;
  18. while (fast != null && fast.next != null) {
  19. slow = slow.next;
  20. fast = fast.next.next;
  21. }
  22. ListNode newHead = reverse(slow);
  23. while (pHead != null && newHead != null) {
  24. if (pHead.val != newHead.val) {
  25. return false;
  26. }
  27. pHead = pHead.next;
  28. newHead = newHead.next;
  29. }
  30. return true;
  31. }
  32. private static ListNode reverse(ListNode head) {
  33. if (head == null) {
  34. return null;
  35. }
  36. ListNode preHead = new ListNode(0);
  37. while (head != null) {
  38. ListNode temp = preHead.next;
  39. preHead.next = head;
  40. head = head.next;
  41. preHead.next.next = temp;
  42. }
  43. return preHead.next;
  44. }
  45. }

 

 

 

 

 

 

 

 

 

第一章:数组与字符串

1,数组与字符串。

  1. 请实现一个算法,确定一个字符串的所有字符是否全都不同。这里我们要求不允许使用额外的存储结构。
  2. 给定一个string iniString,请返回一个bool值,True代表所有字符全都不同,False代表存在相同的字符。保证字符串中的字符为ASCII字符。字符串的长度小于等于3000
  3. 测试样例:
  4. "aeiou"
  5. 返回:True
  6. "BarackObama"
  7. 返回:False

(1)答案和思路:字符串有两种,一种是ASCII字符串(256个),一种是Unicode字符串(65536个)。

这里是ASCII字符串,那么当字符串长度>256的时候一定会有相同的出现了。然后利用这个性质开一个boolean的数组来记录是否出现过。

解法一:估计是牛客网的问题,显示了越界。但是测试用例在自己本地是能够跑出来了的。

  1. import java.util.*;
  2. public class Different {
  3. public boolean checkDifferent(String iniString) {
  4. // write code here
  5. boolean[] charset = new boolean[256];
  6. for(int i = 0;i < iniString.length(); i++){
  7. int val = iniString.charAt(i);
  8. if(charset[val]){
  9. return false;
  10. }
  11. charset[val] = true;
  12. }
  13. return true;
  14. }
  15. }

解法二:

  1. import java.util.*;
  2. public class Different {
  3. public boolean checkDifferent(String str) {
  4. // write code here
  5. for(int i = 0; i < str.length(); i++){
  6. for(int j = i + 1; j < str.length(); j++){
  7. if(str.charAt(i) == str.charAt(j)) return false;
  8. }
  9. }
  10. return true;
  11. }
  12. }

 

2,反转字符串

  1. 请实现一个算法,在不使用额外数据结构和储存空间的情况下,翻转一个给定的字符串(可以使用单个过程变量)。
  2. 给定一个string iniString,请返回一个string,为翻转后的字符串。保证字符串的长度小于等于5000
  3. 测试样例:
  4. "This is nowcoder"
  5. 返回:"redocwon si sihT"

 

(1)答案和思路:StringBuffer本身有reverse()函数。利用好这个功能。String变成StringBuffer。通过new StirngBuffer。反之,通过.toString();

所犯错误:.length少了(),.toString少了();

答案:

  1. public class Reverse {
  2. public String reverseString(String iniString) {
  3. // write code here
  4. StringBuffer tmp = new StringBuffer(iniString);
  5. tmp = tmp.reverse();
  6. return tmp.toString();
  7. }
  8. }

 

3,确定两个字符串乱序同构

  1. 给定两个字符串,请编写程序,确定其中一个字符串的字符重新排列后,能否变成另一个字符串。这里规定大小写为不同字符,且考虑字符串重点空格。
  2. 给定一个string stringA和一个string stringB,请返回一个bool,代表两串是否重新排列后可相同。保证两串的长度都小于等于5000
  3. 测试样例:
  4. "This is nowcoder","is This nowcoder"
  5. 返回:true
  6. "Here you are","Are you here"
  7. 返回:false

(1)答案和思路:把他们变成char[], 然后排序,再变成string。比较一下就可以了。

答案1:

  1. import java.util.*;
  2. public class Same {
  3. public boolean checkSam(String stringA, String stringB) {
  4. // write code here
  5. if (stringA == null || stringB == null) {
  6. return false;
  7. }
  8. int lengthA = stringA.length();
  9. int lengthB = stringB.length();
  10. if (lengthA != lengthB) {
  11. return false;
  12. }
  13. char[] temp = stringA.toCharArray();
  14. Arrays.sort(temp);
  15. String a = new String(temp);
  16. temp = stringB.toCharArray();
  17. Arrays.sort(temp);
  18. String b = new String(temp);
  19. if (a.equals(b)) {
  20. return true;
  21. }
  22. return false;
  23. }
  24. }

思路2:假设只是ASCII码。开一个256的数组,记录第一个出现的个数。因为先判断了长度相等。所以,第二个字符串出现的字符那里个数--,如果不等一定会出现个数减到负数。注意这里的前提是256数组。但是复杂度更低。一遍过去就能够结束。

  1. import java.util.*;
  2. public class Same {
  3. public boolean checkSam(String stringA, String stringB) {
  4. // write code here
  5. if (stringA == null || stringB == null) {
  6. return false;
  7. }
  8. int lengthA = stringA.length();
  9. int lengthB = stringB.length();
  10. if (lengthA != lengthB) {
  11. return false;
  12. }
  13. int[] num = new int[256];
  14. for (int i = 0; i < lengthA; i++) {
  15. num[stringA.charAt(i)]++;
  16. }
  17. for (int i = 0; i < lengthA; i++) {
  18. num[stringB.charAt(i)]--;
  19. if (num[stringB.charAt(i)] < 0) {
  20. return false;
  21. }
  22. }
  23. return true;
  24. }
  25. }

 

4,空格替换为%20

  1. 请编写一个方法,将字符串中的空格全部替换为“%20”。假定该字符串有足够的空间存放新增的字符,并且知道字符串的真实长度(小于等于1000),同时保证字符串由大小写的英文字母组成。
  2. 给定一个string iniString 为原始的串,以及串的长度 int len, 返回替换后的string
  3. 测试样例:
  4. "Mr John Smith”,13
  5. 返回:"Mr%20John%20Smith"
  6. ”Hello World”,12
  7. 返回:”Hello%20%20World”

(1)答案和思路:利用stringbuffer来进行追加操作。知识点:StringBuffer的追加append()。里面可以使字符串也可以是字符。所以特别方便。

  1. import java.util.*;
  2. public class Replacement {
  3. public String replaceSpace(String iniString, int length) {
  4. // write code here
  5. // Error: if (iniString == null || iniString.length == 0) {
  6. if (iniString == null || iniString.length() == 0) {
  7. return iniString;
  8. }
  9. StringBuffer sb = new StringBuffer();
  10. for (int i = 0; i < iniString.length(); i++) {
  11. if (iniString.charAt(i) == ' ') {
  12. sb.append("%20");
  13. } else {
  14. sb.append(iniString.charAt(i));
  15. }
  16. }
  17. return new String(sb);
  18. }
  19. }

 

 5,字符串压缩(把字符串变成他加上他的连续个数)

  1. 利用字符重复出现的次数,编写一个方法,实现基本的字符串压缩功能。比如,字符串“aabcccccaaa”经压缩会变成“a2b1c5a3”。若压缩后的字符串没有变短,则返回原先的字符串。
  2. 给定一个string iniString为待压缩的串(长度小于等于3000),保证串内字符均由大小写英文字母组成,返回一个string,为所求的压缩后或未变化的串。
  3. 测试样例
  4. "aabcccccaaa"
  5. 返回:"a2b1c5a3"
  6. "welcometonowcoderrrrr"
  7. 返回:"welcometonowcoderrrrr"

(1)答案和思路:利用stingbuffer来append。StringBuffer可以追加字符串,字符,整数。关键地方:要判断压缩得到的字符串和原来字符串长度,如果大于了,那么说明无需压缩。

  1. import java.util.*;
  2. public class Zipper {
  3. public String zipString(String iniString) {
  4. // write code here
  5. if (iniString == null || iniString.length() == 0) {
  6. return iniString;
  7. }
  8. StringBuffer sb = new StringBuffer();
  9. for (int i = 0; i < iniString.length();) {
  10. char c = iniString.charAt(i);
  11. int count = 0;
  12. while (i < iniString.length() && c == iniString.charAt(i)) {
  13. count++;
  14. i++;
  15. }
  16. sb.append(c);
  17. sb.append(count);
  18. }
  19. if (sb.length() > iniString.length()) {
  20. return iniString;
  21. }
  22. return new String(sb);
  23. }
  24. }

 

6,像素翻转(矩阵旋转90度)

  1. 题目描述
  2. 有一副由NxN矩阵表示的图像,这里每个像素用一个int表示,请编写一个算法,在不占用额外内存空间的情况下(即不使用缓存矩阵),将图像顺时针旋转90度。
  3. 给定一个NxN的矩阵,和矩阵的阶数N,请返回旋转后的NxN矩阵,保证N小于等于500,图像元素小于等于256
  4. 测试样例:
  5. [[1,2,3],[4,5,6],[7,8,9]],3
  6. 返回:[[7,4,1],[8,5,2],[9,6,3]]

(1)答案和思路: 最好记的办法matix[位置1][位置2] = matrix[n - 1 - 位置2][位置1]。一层一层处理,从外往里。其实i代表的就是处理到第几层了。j的范围会从i到n-1-i.

  1. import java.util.*;
  2. public class Transform {
  3. public int[][] transformImage(int[][] mat, int n) {
  4. // write code here
  5. if (null == mat || mat.length == 0) {
  6. return mat;
  7. }
  8. // 最好记的办法matix[位置1][位置2] = matrix[n - 1 - 位置2][位置1];
  9. for (int i = 0; i < n/ 2; ++i) {
  10. for (int j = i; j < n - i - 1; j++) {
  11. int top = mat[i][j];
  12. mat[i][j] = mat[n - 1 - j][i];
  13. mat[n - 1 - j][i] = mat[n - 1 - i][n - 1 - j];
  14. mat[n - 1 - i][n - 1 - j] = mat[j][n - 1 - i];
  15. mat[j][n - 1 - i] = top;
  16. }
  17. }
  18. return mat;
  19. }
  20. }

 7,清除行列(某一个元素为0,那么这一行这一列都要变成0)

  1. 请编写一个算法,若MxN矩阵中某个元素为0,则将其所在的行与列清零。
  2. 给定一个MxNint[][]矩阵(C++中为vector>)mat和矩阵的阶数n,请返回完成操作后的int[][]矩阵(C++中为vector>),保证n小于等于300,矩阵中的元素为int范围内。
  3. 测试样例:
  4. [[1,2,3],[0,1,2],[0,0,1]]
  5. 返回:[[0,0,3],[0,0,0],[0,0,0]]

(1)答案和思路:先把要化为0的行和列记下来。遍历的时候,只要是行或者列需要化为,那么mat[i][j]都要变为0.

  1. import java.util.*;
  2. public class Clearer {
  3. public int[][] clearZero(int[][] mat, int n) {
  4. // write code here
  5. int[] row = new int[n];
  6. int[] cal = new int[mat[0].length];
  7. for (int i = 0; i < n; ++i) {
  8. for (int j = 0; j < mat[0].length; ++j) {
  9. if (mat[i][j] == 0) {
  10. row[i] = 1;
  11. cal[j] = 1;
  12. }
  13. }
  14. }
  15. // row
  16. for (int i = 0; i < n; ++i) {
  17. for (int j = 0; j < mat[0].length; ++j) {
  18. if (row[i] == 1 || cal[j] == 1) {
  19. mat[i][j] = 0;
  20. }
  21. }
  22. }
  23. return mat;
  24. }
  25. }

 8,翻转子串(看一个子串是否是另一个移位旋转而成)

  1. 题目描述
  2. 假定我们都知道非常高效的算法来检查一个单词是否为其他字符串的子串。请将这个算法编写成一个函数,给定两个字符串s1s2,请编写代码检查s2是否为s1旋转而成,要求只能调用一次检查子串的函数。
  3. 给定两个字符串s1,s2,请返回bool值代表s2是否由s1旋转而成。字符串中字符为英文字母和空格,区分大小写,字符串长度小于等于1000
  4. 测试样例:
  5. "Hello world","worldhello "
  6. 返回:false
  7. "waterbottle","erbottlewat"
  8. 返回:true

(1)答案和思路:加入s1 = xy. s2 = yx.那么s1 + s1 = xyxy。那么中间构成了s2(yx)。

  1. import java.util.*;
  2. public class ReverseEqual {
  3. public boolean checkReverseEqual(String s1, String s2) {
  4. // write code here
  5. s1 = s1 + s1;
  6. if (s1.contains(s2)) {
  7. return true;
  8. }
  9. return false;
  10. }
  11. }

 

二刷Cracking the Coding Interview(CC150第五版)的更多相关文章

  1. 【读书笔记】Cracking the Code Interview(第五版中文版)

    导语 所有的编程练习都在牛客网OJ提交,链接: https://www.nowcoder.com/ta/cracking-the-coding-interview 第八章 面试考题 8.1 数组与字符 ...

  2. Cracking the coding interview

    写在开头 最近忙于论文的开题等工作,还有阿里的实习笔试,被虐的还行,说还行是因为自己的水平或者说是自己准备的还没有达到他们所需要人才的水平,所以就想找一本面试的书<Cracking the co ...

  3. Cracking the coding interview 第一章问题及解答

    Cracking the coding interview 第一章问题及解答 不管是不是要挪地方,面试题具有很好的联系代码总用,参加新工作的半年里,做的大多是探索性的工作,反而代码写得少了,不高兴,最 ...

  4. Cracking the Coding Interview(Trees and Graphs)

    Cracking the Coding Interview(Trees and Graphs) 树和图的训练平时相对很少,还是要加强训练一些树和图的基础算法.自己对树节点的设计应该不是很合理,多多少少 ...

  5. Cracking the Coding Interview(Stacks and Queues)

    Cracking the Coding Interview(Stacks and Queues) 1.Describe how you could use a single array to impl ...

  6. 《Cracking the Coding Interview》读书笔记

    <Cracking the Coding Interview>是适合硅谷技术面试的一本面试指南,因为题目分类清晰,风格比较靠谱,所以广受推崇. 以下是我的读书笔记,基本都是每章的课后习题解 ...

  7. Cracking the coding interview目录及资料收集

    前言 <Cracking the coding interview>是一本被许多人极力推荐的程序员面试书籍, 详情可见:http://www.careercup.com/book. 第六版 ...

  8. Cracking the Coding Interview 150题(二)

    3.栈与队列 3.1 描述如何只用一个数组来实现三个栈. 3.2 请设计一个栈,除pop与push方法,还支持min方法,可返回栈元素中的最小值.pop.push和min三个方法的时间复杂度必须为O( ...

  9. 《Cracking the Coding Interview》——第18章:难题——题目12

    2014-04-29 04:36 题目:最大子数组和的二位扩展:最大子矩阵和. 解法:一个维度上进行枚举,复杂度O(n^2):另一个维度执行最大子数组和算法,复杂度O(n).总体时间复杂度为O(n^3 ...

随机推荐

  1. SQL函数汇总【精选篇】

    1.绝对值   SQL:select abs(-1) value  O:select abs(-1) value from dual  2.取整(大)   S:select ceiling(-1.00 ...

  2. .NET跨平台之旅:corehost 是如何加载 coreclr 的

    在前一篇博文中,在好奇心的驱使下,探秘了 dotnet run ,发现了神秘的 corehost  —— 运行 .NET Core 应用程序的幕后英雄.有时神秘就是一种诱惑,神秘的 corehost ...

  3. 【WPF】释放图像资源, [删除时报另一进程占用]

    源:zhantianyou CODE private BitmapImage ReturnBitmap(string destFile) { // Read byte[] from png file ...

  4. Android换肤技术总结

    原文出处: http://blog.zhaiyifan.cn/2015/09/10/Android%E6%8D%A2%E8%82%A4%E6%8A%80%E6%9C%AF%E6%80%BB%E7%BB ...

  5. C# 获取当前域的路径值

    做域认证的情况下, 要先获取域的path, 可以先用代码获取当前域的path. string pathCur = "LDAP://RootDSE"; DirectoryEntry ...

  6. Linux创建WiFi热点

    手机流量用完,需要开WiFi,由于是LinuxMint,感觉配置还算容易,找到一个不错的教程,收藏一下,以备后用.除了修改配置文件那步在我的电脑不需要外其他基本正确,而且Mint本来就衍生自Ubunt ...

  7. Python Logging模块的简单使用

    前言 日志是非常重要的,最近有接触到这个,所以系统的看一下Python这个模块的用法.本文即为Logging模块的用法简介,主要参考文章为Python官方文档,链接见参考列表. 另外,Python的H ...

  8. Nginx在线服务状态下平滑升级或新增模块的详细操作

    今天应开发的需求,需要在Nginx增加一个模块,并不能影响现有的业务,所以就必须要平滑升级Nginx,好了,不多说了 1:查看现有的nginx编译参数 /usr/local/nginx/sbin/ng ...

  9. laydate兼容bootstrap

    因为Bootstrap使用了 * {box-sizing:border-box;}来reset浏览器的默认盒子模型.所以加上以下代码就可以兼容Bootstrap了 <style type=&qu ...

  10. .gitignore过滤个人配置

    git还是一个很好使用的版本工具.所以用eclipse做自己的小玩意儿,在多台电脑之间同步的时候我经常会使用它.. 但是有个问题..不同电脑的eclipse的个人配置稍微有那么一点点的不同..比如有几 ...