算法小题目
1、X=10,Y=85,D=30 (步长),X+N*D>=Y
public int solution(int X, int Y, int D) { if((Y-X)%D==0) return (Y-X)/D; else return (Y-X)/D+1; }
2、找出缺少的正整数
public int F(int[] A) { int[] positive = new int[A.Length+1]; int pIndex = 1; A = Xier(A); for (int i = 0; i < A.Length; i++) { if (A[i] >= 0) { positive[pIndex] = A[i];// 第一个数0 pIndex++; } } for (int i = 0; i < positive.Length; i++) { if (i == positive.Length - 1) { return positive[positive.Length - 1] + 1; } else { if (positive[i] + 1 < positive[i + 1]) { return positive[i] + 1; } } } return positive[positive.Length-1]+1; } public int[] Xier(int[] A) { for (int gap = A.Length; gap > 0; gap/=2) { for (int i = gap; i < A.Length; i++) { int temp = A[i]; int j = i - gap; while (j >= 0 && temp < A[j]) { A[j + gap] = A[j]; j -= gap; } A[j + gap] = temp; } } return A; }
3、找出数组中不同值数量
public int D(int[] A) { int count = 0; A = Xier(A); if (A.Length > 0) { count = 1; for (int i = 0; i < A.Length - 1; i++) { if (A[i] != A[i + 1]) { count++; } } } return count; }
4、求出A到B中有多少数可以 X%K==0
public int S(int A,int B,int K) { //方法1 时间复杂度最高,超时 //int index = 0; //for (int i = A; i <= B; i++) //{ // if (i % K == 0) { index++; } //} //return index; //方法2 时间复杂度(O(B-A)/K) //int flag = 0; //if (A % K == 0) //{ // flag = A; //} //else //{ // flag = (A / K + 1) * K; //} //int index = 0; //for (int i= flag; i <= B; i+=K) //{ // if (i % K == 0) { index++; } //} //return index; //方法3 int i = B / K; int j = A / K; if (A % K == 0) { return i - j + 1; } else { return i - j; } }