- 在一组数的编码中,若任意两个相邻的代码只有一位二进制数不同, 则称这种编码为格雷码(Gray Code),请编写一个函数,使用递归的方法生成N位的格雷码。
给定一个整数n,请返回n位的格雷码,顺序为从0开始。
测试样例:
1
返回:[“0”,”1”]
import java.util.*;
public class GrayCode {
public String[] getGray(int n) {
// write code here
// produce 2^n grade codes
String[] graycode = new String[(int) Math.pow(2, n)];
if (n == 1) {
graycode[0] = "0";
graycode[1] = "1";
return graycode;
}
String[] last = getGray(n - 1);
for (int i = 0; i < last.length; i++) {
graycode[i] = "0" + last[i];
graycode[graycode.length - 1 - i] = "1" + last[i];
}
return graycode;
}
}
参考博客:http://blog.youkuaiyun.com/beiyeqingteng/article/details/7044471
-
春节期间小明使用微信收到很多个红包,非常开心。在查看领取红包记录时发现,某个红包金额出现的次数超过了红包总数的一半。请帮小明找到该红包金额。写出具体算法思路和代码实现,要求算法尽可能高效。
给定一个红包的金额数组gifts及它的大小n,请返回所求红包的金额。
测试样例:
[1,2,3,2,2],5
返回:2
//自己写的代码,有问题,没有通过测试
import java.util.*;
public class Gift {
public int[] nums = null;
public int getValue(int[] gifts, int n) {
// write code here
nums = gifts;
quickSort(nums,0,gifs.length-1);
int pos = gifts.length/2;
return gifts[pos];
}
public static void quickSort(int[] money,int left,int right){
int i,j,key,t;
if(left > right){
return;
}
i = left;
j = right;
key = money[left];
while(i!=j){
while(money[j] >= key && i < j){
j--;
}
while(money[i] <= key && i < j){
i++;
}
if(i < j){
t = money[i];
money[i] = money[j];
money[j] = t;
}
}
quickSort(money,left,i-1);
quickSort(money,i+1,right);
}
}