Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
First solution
// Created by xin cao on 2018/05/02.
// Copyright © 2018年 xin cao. All rights reserved.
int* twoSum(int* nums, int numsSize, int target)
{
int i = 0;
int j = 0;
int n = numsSize;
int* result = NULL;
for(i = 0; i < n; i++)
{
for(j= i+1; j< n; j++)
{
if(target == nums[i] + nums[j])
{
result = (int*)malloc(sizeof(int) * 2);
result[0] = i;
result[1] = j;
printf("%d,%d\n",result[0],result[1]);
return result;
}
}
}
return 0;
}
Second solution
/*HASH table */
int* twoSum(int* nums, int numsSize, int target)
{
int min = 2345678;
int i = 0;
for(i = 0; i < numsSize; i++)
{
if(nums[i] < min)
min = nums[i];
}
int max = target - min;
int len = max - min + 1;
int* table = (int*)malloc(sizeof(int) * len);
int* indice = (int*)malloc(sizeof(int) * 2);
for(i = 0; i < len; i++)
table[i] = -1;
for(i =0; i < numsSize; i++)
if(nums[i] - min < len)
{
if(table[target - nums[i] - min] != -1)
{
indice[0] = table[target-nums[i] - min];
indice[1] = i;
printf("%d,%d\n",indice[0],indice[1]);
return indice;
}
table[nums[i]-min] = i;
}
free(table);
printf("%d,%d\n",indice[0],indice[1]);
return indice;
}
Third solution
/*quick sort solution*/
#include<stdio.h>
#include<mm_malloc.h>
void quicksort(int* nums, int begin, int end){
int l, r, t;
int temp=nums[begin];
l=begin;r=end;
if(l>=r)return;
while(l!=r){
while(l<r && nums[r]>=temp)r--;
while(l<r && nums[l]<=temp)l++;
if(l<r){
t=nums[r];
nums[r]=nums[l];
nums[l]=t;
}
}
nums[begin]=nums[l];
nums[l]=temp;
quicksort(nums,begin,l-1);
quicksort(nums,l+1,end);
}
int* twoSum(int* nums, int numsSize, int target) {
int i,a,b,begin=0,end=numsSize-1,k;
quicksort(nums, 0, numsSize-1);
printf("%d,%d,%d\n",nums[0],nums[1],nums[2]);
while(begin<end){
while(nums[begin]+nums[end]>target)end--;
//if(nums[begin]+nums[end]==target)break;
while(nums[begin]+nums[end]<target)begin++;
if(nums[begin]+nums[end]==target)break;
}
a=nums[begin];b=nums[end];
printf("a=%d\n",a);
printf("b=%d\n",b);
int *indice = (int*)malloc(2*sizeof(int));
for(i=0;i<numsSize;i++){
if(nums[i]==a){
indice[0]=i;
}
if(nums[i]==b)indice[1]=i;
}
printf("%d,%d",indice[0],indice[1]);
return indice;
}
int main()
{
int* nums, numsSize, target;
int *a = (int*)malloc(2*sizeof(int));
int z[3]={3,2,4};
nums=&z[0];
target=6;
numsSize=3;
twoSum(nums, numsSize, target);
}