面試題64. 求1+2+…+n
求 1+2+...+n ,要求不能使用乘除法、for、while、if、else、switch、case等關鍵字及條件判斷語句(A?B:C)
注:
這個特性實際叫做“驟死性評估”,是一種語言特性,即左側的表達式爲假時整個表達式後續將不再進行評估。
這也就是爲什麼不要重載&&,||,和逗號操作符的原因,因爲重載之後變爲函數語義,編譯器將不再保證驟死性評估。
//遞歸
class Solution {
public int sumNums(int n) {
int sum = n;
boolean flag = n > 0 && (sum += sumNums(n-1)) > 0;
return sum;
}
}
//等差數列
class Solution {
public int sumNums(int n) {
return (int) (Math.pow(n, 2) + n) >> 1;
}
}
面試題06. 從尾到頭打印鏈表
class Solution {
public int[] reversePrint(ListNode head) {
Stack<Integer> stack = new Stack<>();
while(head != null){
stack.push(head.val);
head = head.next;
}
int[] res = new int[stack.size()];
int i = 0;
while(!stack.isEmpty()){
res[i++] = stack.pop();
}
return res;
}
}
78. 子集
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
res.add(new ArrayList<>());
for(int i = 0;i < nums.length;i++){
int all = res.size();
for(int j = 0; j < all; j++){
List<Integer> tmp = new ArrayList<>(res.get(j));
tmp.add(nums[i]);
res.add(tmp);
}
}
return res;
}
}
//遞歸
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> output = new ArrayList();
output.add(new ArrayList<Integer>());
for (int num : nums) {
List<List<Integer>> newSubsets = new ArrayList();
for (List<Integer> curr : output) {
newSubsets.add(new ArrayList<Integer>(curr){{add(num);}});
}
for (List<Integer> curr : newSubsets) {
output.add(curr);
}
}
return output;
}
}
344. 反轉字符串
“異或”運算。
運算規則:0^0=0; 0^1=1; 1^0=1; 1^1=0;
即:參加運算的兩個對象,如果兩個相應位爲“異”(值不同),則該位結果爲1,否則爲0。
//異或運算交換兩個值 a = a^b b = a^b
// a = a^b
// b = 原來的a
// a = 原來的b
//位運算省去了O(1)的空間 同時運算的速度更快 但是必須注意,如果a 和 b是指針指向同一地址時,
//此時a=b,a^b會將該地址的值變爲0,這可就沒有實現交換,反而出現錯誤了,注意使用環境,在此題中無影響。
class Solution {
public void reverseString(char[] s) {
int n = s.length;
for (int i = 0; i < n / 2; ++i) {
int j = n - 1 - i;
s[i] ^= s[j];
s[j] ^= s[i];
s[i] ^= s[j];
}
}
}
class Solution {
public void reverseString(char[] s) {
if(s.length == 0){
return;
}
char temp=' ';
for(int i=0;i<s.length/2;i++){
temp=s[i];
s[i]=s[s.length-i-1];
s[s.length-i-1]=temp;
}
}
}
//遞歸
class Solution {
public void helper(char[] s, int left, int right) {
if (left >= right) return;
char tmp = s[left];
s[left++] = s[right];
s[right--] = tmp;
helper(s, left, right);
}
public void reverseString(char[] s) {
helper(s, 0, s.length - 1);
}
}
你知道的越多,你不知道的越多。
有道無術,術尚可求,有術無道,止於術。
如有其它問題,歡迎大家留言,我們一起討論,一起學習,一起進步