前一篇文章是我做的题 这是剩余的三道,都很基础。
1. Write a method to generate the nth number of the Fibonacci sequence.
Defined as
f(0)=0
f(1)=1
f(n)=f(n-1)+ f(n-2) where n>1
Sequence is 0 1 1 2 3 5…
基础题,递归或者非递归方式
public class Fib { public static int fib(int n) { int result; if (n <= 1) { return n; } else { result = fib(n - 2) + fib(n - 1); } return result; } public static int getNthFib(int n) { if (n <= 1) return n; // error & default input int fn2 = 1, fn1 = 1, index = 2; // starts from 2 while (index < n) { // fn2 means f(n-2), fn1 means f(n-1) fn1 = fn1 + fn2; fn2 = fn1 - fn2; index++; } return fn1; }
}
注意fn1和fn2递增的赋值方式,比引入tmp变量更好的解决方案。
3. Implement an algorithm to find the nth to last element of a singly linked list
findNth(0) would return the last element of the list
findNth(1) would return the second to last element of the list
public Node findNthToLast(Node node)
{
}
基本题,考察两个游标遍历单链表,需要注意边界条件和限制。
public class LastNth { public static int findNth(Node head, int n) { if (head == null) return -1; // error, list is null Node fast = head, slow = head; int index = 1; while (index <= n) { if (fast.next != null) { fast = fast.next; } else { return -1; // error, list has less than n elements } index++; } while (fast.next != null) { fast = fast.next; slow = slow.next; } return slow.val; } }
4. Write a method to decide if two strings are anagrams or not.
基本题 需要考虑是否是ASCII码(256位)如果是的话那么定义相应位数的数组进行存储
public class AnagramStr { public static boolean isAnagram(String s1, String s2) { int len1 = s1.length(), len2 = s2.length(); if (len1 != len2) // not same length return false; int[] letters = new int[256]; for (int i = 0; i < letters.length; i++) { letters[i] = 0; } for (char c : s1.toCharArray()) { ++letters[c]; } for (char c : s2.toCharArray()) { --letters[c]; } for (int i = 0; i < letters.length; i++) { if (letters[i] != 0) { return false; } } return true; } }
如果不限于ASCII,可以使用map来对不确定字符数进行统计。
public static boolean areAnagram(String s1, String s2) { int len1 = s1.length(), len2 = s2.length(); HashMap<Character, Integer> map1 = new HashMap<Character, Integer>(), map2 = new HashMap<Character, Integer>(); if (len1 != len2) // not same length return false; for (char c : s1.toCharArray()) { if (map1.containsKey(c)) { map1.put(c, map1.get(c) + 1); } else { map1.put(c, 1); } } for (char c : s2.toCharArray()) { if (map2.containsKey(c)) { map2.put(c, map2.get(c) + 1); } else { map2.put(c, 1); } } if (!map1.equals(map2)) return false; return true; }
还有一个思路是对两个string进行排序,然后从头往后遍历。