原题:
Given a sorted array, two integers k
and x
, find the k
closest elements to x
in the array. The result should also be sorted in ascending order. If there is a tie, the smaller elements are always preferred.
Example 1:
Input: [1,2,3,4,5], k=4, x=3 Output: [1,2,3,4]
Example 2:
Input: [1,2,3,4,5], k=4, x=-1 Output: [1,2,3,4]
Note:
- The value k is positive and will always be smaller than the length of the sorted array.
- Length of the given array is positive and will not exceed 104
- Absolute value of elements in the array and x will not exceed 104
由于开始没看清题目就开始写,导致最后推倒重做。。。 烦躁。。
代码如下:
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int* findClosestElements(int* arr, int arrSize, int k, int x, int* returnSize) {
*returnSize=k;
int n;
for(n=0;n<arrSize;n++)
{
if(*(arr+n)>x)
break;
}
//printf("%d",n);
struct listnode
{
int val;
struct listnode* next;
};
struct listnode* front;
struct listnode* last;
front=(struct listnode*)malloc(sizeof(struct listnode));
last=(struct listnode*)malloc(sizeof(struct listnode));
front->next=NULL;
last->next=NULL;
struct listnode* head;
head=last;
struct listnode* p1;
int kf=1;
int ka=0;
for(int m=0;k>0;k--,m++)
{
p1=(struct listnode *)malloc(sizeof(struct listnode));
//printf("%d,%d,",n-kf,n+ka);
if(n-kf>=0&&n+ka<arrSize)
{
if((x-*(arr+n-kf))<=(*(arr+n+ka)-x))
{
p1->val=*(arr+n-kf);
p1->next=front->next;
front->next=p1;
printf("%d",*(arr+n-kf)-x);
printf("%d",*(arr+n+ka)-x);
kf++;
}
else
{
p1->val=*(arr+n+ka);
last->next=p1;
last=p1;
p1->next=NULL;
printf("%d",*(arr+n-kf)-x);
printf("%d",*(arr+n+ka));
ka++;
}
continue;
}
if(n-kf<0)
{
p1->val=*(arr+n+ka);
last->next=p1;
last=p1;
p1->next=NULL;
ka++;
continue;
}
if(n+ka>=arrSize)
{
p1->val=*(arr+n-kf);
p1->next=front->next;
front->next=p1;
kf++;
continue;
}
}
n=0;
int *result;
result=(int*)malloc(sizeof(int)*(*returnSize));
for(;n<*returnSize;n++)
{
if(front->next!=NULL)
{
*(result+n)=front->next->val;
front=front->next;
}
else
{
break;
}
}
for(;n<*returnSize;n++)
{
if(head->next!=NULL)
{
*(result+n)=head->next->val;
head=head->next;
}
}
return result;
}
现在想想,其实用一个链表一个数组就好了。
毕竟开始想写一个双端,不过后来感觉没必要就算了。
算法很简单,就是依次的比较就好。定位要准确!