【leetcode】第一天

两数之和

leetcode页面

问题描述:给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

  1. 暴力算法

    					逐个计算法,复杂度高。
    

从第一个数开始和后面的数进行求和,没有符合目标值的情况则对第二个数进行同样的操作,直到找到目标值。

int* twoSum(int* nums, int numsSize, int target, int* returnSize){
    int *a = (int *)malloc(sizeof(int) * 2);
    int i, j;
    for (i = 0; i < numsSize - 1; i++) {
        for (j = i + 1; j < numsSize; j++) {
            if (nums[i] + nums[j] == target) {
                a[0] = i;
                a[1] = j;
                *returnSize = 2;
                return a;
            }
        }
    }               
    *returnSize = 0;
    return a;
}

在这里插入图片描述
2. other

                                   字典法

将所有的值存入字典中,求出差值以后直接在字典中查找。复杂度为o(n).

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        hashmap = {}
        for index, num in enumerate(nums):
            another_num = target - num
            if another_num in hashmap:
                return [hashmap[another_num], index]
            hashmap[num] = index
        return None

在这里插入图片描述

  1. 引申

如果所给数组已经是排好序的

                       			双指针法

如果所给数组已经是排好序的,所以我们可以采取”小则加大数,大则加小数“的方法,来寻找目标值。

a b c d e f g h

        ↑                                                                                                                                                                                 ↑

       设置双指针,分别指向第一个数和最后一个数字,对他们进行求和,【关键处】如果和小于目标值,证明数字需要增大,则对较小的数字进行替换,左指针右移。如果和大于目标值,则较大的数字进行替换,右指针左移。以此类推,知道两个指针所指向的数字的和等于目标值。输出此时指针所指向的元素的下标。

                                             大大减小了复杂度。

本题目也可以对数组排序后运用该方法,需要注意的是最后需要返回排序前数组的下标,所以需要对下标进行排序,实现代码如下:

int* twoSum(int* nums, int numsSize, int target, int* returnSize){
int a=0;
int b=numsSize-1;
int *result = (int *)malloc(sizeof(int) * 2);
int m,i,j,temp,value=0;
int *ids = (int *)malloc(sizeof(int) * numsSize);

for (m=0;m<numsSize;m++)
{
    ids[m]=m;
}

for(i=0; i<b; i++){
        for(j=0; j<b-i; j++){
            if (nums[j]>nums[j+1])
                {
                value=nums[j+1];
                nums[j+1]=nums[j];
                nums[j]=value;
                temp=ids[j+1];
                ids[j+1]=ids[j];
                ids[j]=temp;
                }
        }
}
for(i=0; i<numsSize; i++){
        printf("%d ", ids[i]);
    }
 
while (a!=b)
{
    if (nums[a]+nums[b]<target)
        a++;
    else if (nums[a]+nums[b]>target)
        b--;
    else
        {
         result[0]=ids[a];
         result[1]=ids[b];
         * returnSize=2;
         
         return result;
        }         
} 
 * returnSize=0;

return result;
}

leetcode判定结果
4. Tips

        如果需要对数组下标排序,要事先初始化一个下标序列。
        学会使用动态分配数组空间
       寻找固定的值为了减少复杂度,可以使用字典。

发布了3 篇原创文章 · 获赞 1 · 访问量 21

猜你喜欢

转载自blog.csdn.net/qq_42803942/article/details/104999685
今日推荐