/**
* Note: The returned array must be malloced, assume caller calls free().
*/
void exchange(int *a, int* b) {
int temp;
temp = *a;
*a = *b;
*b = temp;
}
int partition (int* arr, int si, int ei) {
int x = arr[ei];
int i = si-1;
int j;
for (j = si; j < ei; j++) {
if (arr[j] <= x) {
i++;
exchange(&arr[j], &arr[i]);
}
}
exchange (&arr[i+1], &arr[ei]);
return i+1;
}
void quickSort (int* arr, int si, int ei) {
int pi;
if (si < ei) {
pi = partition(arr, si, ei);
quickSort(arr, si, pi -1);
quickSort(arr, pi+1, ei);
}
}
int* twoSum(int* nums, int numsSize, int target) {
int start = 0, end = numsSize-1, sum,a, b;
int *temp = malloc(numsSize*sizeof(int));
int k;
for (k=0; k <= end; k++) {
temp[k] = nums[k];
}
int* index = malloc(2*sizeof(int));
quickSort(temp, start, end);
int l;
while (start < end) {
sum = temp[start] + temp[end];
if (sum == target) {
a = temp[start];
b = temp[end];
break;
} else if (sum > target)
end--;
else
start++;
}
int z, y;
for(z = 0; z < numsSize; z++) {
if (nums[z] == a) {
break;
}
}
for (y = 0; y < numsSize; y++) {
if(nums[y] == b && y!=z) {
break;
}
}
if (z < y) {
index[0] = z;
index[1] = y;
}else {
index[0] = y;
index[1] = z;
}
return index;
}
* Note: The returned array must be malloced, assume caller calls free().
*/
void exchange(int *a, int* b) {
int temp;
temp = *a;
*a = *b;
*b = temp;
}
int partition (int* arr, int si, int ei) {
int x = arr[ei];
int i = si-1;
int j;
for (j = si; j < ei; j++) {
if (arr[j] <= x) {
i++;
exchange(&arr[j], &arr[i]);
}
}
exchange (&arr[i+1], &arr[ei]);
return i+1;
}
void quickSort (int* arr, int si, int ei) {
int pi;
if (si < ei) {
pi = partition(arr, si, ei);
quickSort(arr, si, pi -1);
quickSort(arr, pi+1, ei);
}
}
int* twoSum(int* nums, int numsSize, int target) {
int start = 0, end = numsSize-1, sum,a, b;
int *temp = malloc(numsSize*sizeof(int));
int k;
for (k=0; k <= end; k++) {
temp[k] = nums[k];
}
int* index = malloc(2*sizeof(int));
quickSort(temp, start, end);
int l;
while (start < end) {
sum = temp[start] + temp[end];
if (sum == target) {
a = temp[start];
b = temp[end];
break;
} else if (sum > target)
end--;
else
start++;
}
int z, y;
for(z = 0; z < numsSize; z++) {
if (nums[z] == a) {
break;
}
}
for (y = 0; y < numsSize; y++) {
if(nums[y] == b && y!=z) {
break;
}
}
if (z < y) {
index[0] = z;
index[1] = y;
}else {
index[0] = y;
index[1] = z;
}
return index;
}
No comments:
Post a Comment