#include <stdio.h> int judge(int *a, int len, int k, int *num1, int *num2); int main(int argc, char **argv) { int test_array[] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; int result = -1; int num1, num2; result = judge(test_array, sizeof(test_array) / sizeof(int), 12, &num1, &num2); if(result == 0) { printf("%d\t%d\n", num1, num2); } else if(result == -1) { printf("can't find"); } else { printf("error"); } } int judge(int *a, int len, int k, int *num1, int *num2) { int *low = NULL; int *high = NULL; int i = 0; int result = -1; if(a == NULL || len < 2) { return result; } if(a[0] >= k) { return result; } while(a[i] <= k && i < len) { i++; } low = a; high = a + i - 1; while(low < high) { *num1 = *low; *num2 = *high; if((*low + *high) == k) { result = 0; break; } else if((*low + *high) > k) { high--; } else if((*low + *high) < k) { low++; } } return result; }
解法二:
#include <iostream> using namespace std; int hash_table[100]; bool judge(int *a, int len, int x) { memset(hash_table, 0, sizeof(hash_table)); for (int i=0; i<len; ++i) { hash_table[x - a[i]] = 1; } for (int i=0; i<len; ++i) { if (hash_table[i] == 1) { return true; } } return false; } int main() { int len = 10; int a[10] = {1, 3, 5, 7, 9, 4, 2, 8, 10, 6}; int x = 19; if (judge(a, len, x)) { cout<<"Yes"<<endl; } else { cout<<"No"<<endl; } system("pause"); return 0; }
2.給定有n個數的數組a,其中有超過一半的數為一個定值,在不進行排序,不開設額外數組的情況下,以最高效的演算法找出這個數。
#include <iostream> using namespace std; int find(int *a, int n) { int t = a[0]; int count = 0; for (int i=0; i<n; ++i) { if (count == 0) { t = a[i]; count = 1; continue; } else { if (a[i] == t) { count++; } else { count--; } } } return t; } int main() { int n = 10; int a[10] = {1, 3, 2, 3, 3, 4, 3, 3, 3, 6}; cout<<find(a, n)<<endl; system("pause"); return 0; }