哈希表:
#define MAX_SIZE 1024
int* intersection(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize)
{
int* hash = (int*)calloc(MAX_SIZE, sizeof(int));
int* res = (int*)calloc(MAX_SIZE, sizeof(int));
for (int i = 0; i < nums1Size; i++) {
if (hash[nums1[i]] == 0) {
hash[nums1[i]]++;
}
}
*returnSize = 0;
for (int i = 0; i < nums2Size; i++) {
if (hash[nums2[i]]) {
hash[nums2[i]]--;
res[(*returnSize)++] = nums2[i];
}
}
return res;
}
排序:
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int cmp(void* a, void* b) {
return *(int*)a - *(int*)b;
}
int* intersection(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize) {
/* 1、判断输入数组是否有空,有则返回 */
if (!nums1 || !nums2) {
*returnSize = 0;
return NULL;
}
/* 2、对输入数组进行排序 */
qsort(nums1, nums1Size, sizeof(int), cmp);
qsort(nums2, nums2Size, sizeof(int), cmp);
/* 3、定义索引cnt、分配返回数组的空间为输入数组的较小者 */
int cnt = 0;
int* ret = (int*)malloc(sizeof(int) * (int)fmin(nums1Size, nums2Size));
/* 4、从头到尾进行比较 */
for (int i = 0, j = 0; i < nums1Size && j < nums2Size; ) {
/* 不相等则进行下一次比较 */
if (nums1[i] < nums2[j]) {
i++;
}
else if (nums1[i] > nums2[j]) {
j++;
}
else {
/* 相等则记录 */
ret[cnt++] = nums1[i];
i++;
j++;
/* 判断是否出现相等元素,减小cnt即可,这样下次记录元素时即可直接覆盖掉 */
if (cnt > 1 && ret[cnt - 1] == ret[cnt - 2]) {
cnt--;
}
}
}
//ret = (int *)realloc(ret, sizeof(int) * cnt);
*returnSize = cnt;
return ret;
}
int pivotIndex(int* nums, int numsSize){
int totalsum = 0, leftsum = 0; //totalsum存放整个数组元素和,leftsum存放左侧元素和
for(int i=0; i
static int answer[100000]={0};
int* productExceptSelf(int* nums, int numsSize, int* returnSize){
*returnSize = numsSize;
int i = 0;
int left[numsSize];
int right[numsSize];
left[0] = 1;
for(i=1;i=0;i--)
{
right[i] = right[i+1]*nums[i+1];//从右往左乘到nums[i]之前停下
}
for(i=0;i
int* masterMind(char* solution, char* guess, int* returnSize){
*returnSize = 2;
int* answer = (int*)calloc(2,sizeof(int));
int hash1[26] = {0};
int hash2[26] = {0};
int i = 0;
for(i=0;i<4;i++)
{
if(solution[i] == guess[i])
{
answer[0]++;
}
else
{
hash1[solution[i] - 'A']++;
hash2[guess[i] - 'A']++;
}
}
for(i=0;i<26;i++)
{
answer[1] += fmin(hash1[i],hash2[i]);//fmin返回两值最小数
}
return answer;
}
void SWAP(int* start,int* end)
{
int* left = start;
int* right = end;
int mid = 0;
while(left
int removeElement(int* nums, int numsSize, int val)
{
int length = 0;
for(int i = 0;i