1.题目描述:
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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
2.解题思路:
先把两个数组进行排序,然后分别使用两个指针low和high指向数组下标0和下标numSize-1,把两个数相加若大于target则移动high指针,小于target则移动low指针。
代码:
int* twoSum(int* nums,int numsSize,int target) {
int *arr = (int *)malloc(sizeof(int)*2);
int *arr1 = (int *)malloc(sizeof(int)*numsSize); //由于数组要经过排序处理,但是返回的是原数组下标,故需要另一个数组复制原数组
for(int i = 0; i < numsSize ;i++)//复制
{
arr1[i] = nums[i];
}
for(int i = 1; i < numsSize; i++)//插入排序
{
for(int j=i;nums[j]<nums[j-1]&&j>0;j--)
{
int temp = nums[j];
nums[j] = nums[j-1];
nums[j-1] = temp;
}
}
int low=0,high=numsSize-1;//定义两个指针分别指向数组两端
while(target != nums[low]+nums[high])
{
if(target > nums[low]+nums[high])
{
low++;
}
else
{
high--;
}
}
for(int i=0;i<numsSize;i++)
{
if(arr1[i] == nums[low])
{
arr[0] = i;
}
if(arr1[i] == nums[high])
{
arr[1] = i;
}
}
return arr;
}
3.解法2:java HashMap
解题思路:把数组元素 作为key,下标为value,循环遍历数组把数组元素和下标放入map中,并判断target-num[i]是否存在map中,若存在则找到该值退出循环。
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<Integer,Integer>();
int[] ret = new int[2];
for (int i = 0; i< nums.length; i++) {
if (map.containsKey(target-nums[i])) {
ret[0] = map.get(target-nums[i]);
ret[1] = i;
break;
}
map.put(nums[i], i);
}
return ret;
}
4.解法3:通过c结构体构建一个HashMap ,解法同解法2
#define maxsize 10000
typedef struct node{
int key;
int value;
}Map;
int* twoSum(int* nums, int numsSize, int target) {
Map *arr = (Map *)malloc(sizeof(Map)*10000);//为了存取效率,故使用了数组。(但浪费了空间)
int *re = (int *)malloc(sizeof(int)*2);
int count=0;//记录存入的Map个数
for(int i=0; i < numsSize; i++)
{
for(int j=0; j < count; j++)//实现map的containsKey
{
if(arr[j].key==target-nums[i])
{
re[0] = arr[j].value;
re[1] = i;
break;
}
}
arr[i].key = nums[i];//实现map的put()
arr[i].value = i;
count++;
}
return re;
}