LeetCode刷题笔记 1

题目:
给定一个整数数组,返回两个数字的索引,使它们相加到特定目标。假设每个输入只有一个解决方案,并且不会两次使用相同的元素。
在这里插入图片描述
我的答案:

#include<stdio.h>
#include<stdlib.h>
#include <malloc.h>
int* twoSum(int* nums, int numsSize, int target) {
    int *a,i,j;
    a = (int *)malloc(sizeof(int)*2);
    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;
                goto here;
            }
        }
    }
    here:return a;
}

需要注意的地方:

  1. malloc申请与释放(free) (c++使用new和delete)
  2. goto 跳出多重循环;或者return跳出
  3. 指针与数组

答案

  1. 方法思路同上(时间复杂度O(n2),空间复杂度O(1))
  2. 哈希表快速查找索引,空间换时间(时间复杂度O(n),空间复杂度O(n))
public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        int complement = target - nums[i];
        if (map.containsKey(complement)) {
            return new int[] { map.get(complement), i };
        }
        map.put(nums[i], i);
    }
    throw new IllegalArgumentException("No two sum solution");
}

猜你喜欢

转载自blog.csdn.net/qq_34623223/article/details/84313912