1、题目描述:
2、题解:
java:递归
public class Code01_MakeNo {
//生成长度为size的达标数组
//达标:对于任意的i<k<j,满足[i] + [j] != [k] * 2
public static int[] makeNo(int size) {
if (size == 1) {
return new int[] {1};
}
//size
//一半长达标来
// 7 :4
//8:4
//[4个奇数][3个偶数]
int halfSize = (size + 1) / 2;
int[] base = makeNo(halfSize);
//base->等长奇数达标来
//base->等长偶数达标来
int[] ans = new int[size];
int index = 0;
for(;index < halfSize;index++) {
ans[index] = base[index] * 2 +1;
}
for(int i =0;index < size;index++,i++) {
ans[index] = base[i] * 2;
}
return ans;
}
//检验函数
public static boolean isValid(int[] arr) {
int N = arr.length;
for(int i = 0;i < N;i++) {
for(int k = i + 1;k <N;k++) {
for (int j = k +1;j < N;j++) {
if (arr[i] + arr[j] == 2 * arr[k]) {
return false;
}
}
}
}
return true;
}
//main函数
public static void main(String[] args) {
System.out.println("test begin");
for (int N = 1;N < 1000;N++) {
int[] arr = makeNo(N);
if (!isValid(arr)) {
System.out.println("Oops!");
}
}
System.out.println("test end");
System.out.println(makeNo(7));
System.out.println(isValid(makeNo(7)));
System.out.println(makeNo(10));
System.out.println(isValid(makeNo(10)));
}
python:
def makeNo(size):
if size == 1:
return [1]
halfsize = (size + 1) // 2
base = makeNo(halfsize)
ans = [0] *size
index = 0
for i in range(halfsize):
ans[i] = base[i] * 2 +1
# ans.append(base[i] * 2 +1)
for i in range(halfsize,size):
ans[i] = base[i- halfsize] * 2
# ans.append(base[i- halfsize] * 2)
return ans
def main():
n = 7
print(makeNo(n))
if __name__ == '__main__':
main()
3、时间复杂度:
master公式:
T(N) = a * T(N/b) + O(N^d)
logb(a) <d , T(N) = O(N^d)
logb(a) >d , T(N) = O(N^logb(a))
logb(a) == d , T(N) = O(N^d *logN)
本题T(N) = T(N/2) + O(N),所以T(N) = O(N)