代码实现:
bool isAnagram(char* s, char* t) {
int record[26] = {0};
for(int i = 0; i < strlen(s);i++)
{
record[s[i] - 'a']++;
}
for(int i = 0; i < strlen(t); i++){
record[t[i] - 'a']--;
}
for(int i = 0; i < 26; i++){
if(record[i] != 0)
return false;
}
return true;
}
思路
先将一个数组变成哈希表,然后将另外一个映射到哈希表上,如果哈希表上有这个,那么就将它移动出来,到新的数组内。
代码实现
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* intersection(int* nums1, int nums1Size, int* nums2, int nums2Size,
int* returnSize) {
int nums1Cnt[1000] = {0};
int lessSize = nums1Size < nums2Size ? nums1Size : nums2Size;
int* result = (int*)calloc(lessSize, sizeof(int));
int resultIndex = 0;
int i;
/* Calculate the number's counts for nums1 array */
for (i = 0; i < nums1Size; i++) {
nums1Cnt[nums1[i]]++;
}
/* Check if the value in nums2 is existing in nums1 count array */
for (i = 0; i < nums2Size; i++) {
if (nums1Cnt[nums2[i]] != 0) {
result[resultIndex] = nums2[i];
resultIndex++;
nums1Cnt[nums2[i]] = 0;
}
}
*returnSize = resultIndex;
return result;
}
思路1:要将每一次的结果给记录下来,当有结果再次重复的时候,说明是循环的了,所以用到哈希表
代码实现
int getsum(int n){
int sum = 0;
while(n){
sum+= (n%10)*(n%10);
n /= 10;
}
return sum;
}
bool isHappy(int n) {
int sum = getsum(n);
int hash[820] = {0};
while(sum != 1){
if(hash[sum] == 1)
return false;
else{
hash[sum]++;
}
sum = getsum(sum);
}
return true;
}
思路二:用双指针,为什么可以用双指针,因为可以将每一次的sum放入链表中,如果是是循环的化,那么就会形成环链,在链表中,学习到了如何找一个环链的入口,所以说这道题可以通过双指针的方法来解决
代码实现
int getsum(int n){
int sum = 0;
while(n){
sum+= (n%10)*(n%10);
n /= 10;
}
return sum;
}
bool isHappy(int n) {
int slow = n;
int fast = n;
do {
slow = getsum(slow);
fast = getsum(getsum(fast));
} while (slow != fast);
return (fast == 1);
}
typedef struct {
int key;
int value;
UT_hash_handle hh; // make this structure hashable
} map;
map* hashMap = NULL;
void hashMapAdd(int key, int value){
map* s;
// key already in the hash?
HASH_FIND_INT(hashMap, &key, s);
if(s == NULL){
s = (map*)malloc(sizeof(map));
s -> key = key;
HASH_ADD_INT(hashMap, key, s);
}
s -> value = value;
}
map* hashMapFind(int key){
map* s;
// *s: output pointer
HASH_FIND_INT(hashMap, &key, s);
return s;
}
void hashMapCleanup(){
map* cur, *tmp;
HASH_ITER(hh, hashMap, cur, tmp){
HASH_DEL(hashMap, cur);
free(cur);
}
}
void hashPrint(){
map* s;
for(s = hashMap; s != NULL; s=(map*)(s -> hh.next)){
printf("key %d, value %d\n", s -> key, s -> value);
}
}
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
int i, *ans;
// hash find result
map* hashMapRes;
hashMap = NULL;
ans = malloc(sizeof(int) * 2);
for(i = 0; i < numsSize; i++){
// key 代表 nums[i] 的值,value 代表所在 index;
hashMapAdd(nums[i], i);
}
hashPrint();
for(i = 0; i < numsSize; i++){
hashMapRes = hashMapFind(target - nums[i]);
if(hashMapRes && hashMapRes -> value != i){
ans[0] = i;
ans[1] = hashMapRes -> value ;
*returnSize = 2;
return ans;
}
}
hashMapCleanup();
return NULL;
}