两数之和

给定一个数组和一个整数,返回数组中两数之和等于目标整数的下标。

假定每种输入只有一个输出,数组中每个元素只能使用一次。

举例:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

python实现

1:暴力法(简单遍历),时间复杂度o(n^2)

def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i in range(0,len(nums)-1):
            for j in range(i+1,len(nums)):
                if(nums[i]+nums[j] == target):
                    return [i,j]

2:利用dict判断,时间复杂度o(n)

def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        dic = {}
        for i in range(0,len(nums)):
            rest = target-nums[i]
            if rest in dic:
                return [dic[rest],i]
            else:
                dic[nums[i]]=i

java实现

1:暴力法,时间复杂度o(n^2)

public int[] twoSum(int[] nums, int target) {
        for(int i=0;i<nums.length;i++) {
             for(int j=i+1;j<nums.length;j++) {
                 if(nums[i] +nums[j] == target){
                     return new int[] {i,j};
                 }
             }
         }
         return null;
    }

2:HashMap方法,时间复杂度o(n)

public int[] twoSum(int[] nums, int target) {
        HashMap<Integer, Integer> container = new HashMap<Integer,Integer>();
         for(int i =0;i<nums.length;i++) {
             int restValue = target-nums[i];
             if(container.containsKey(restValue)) {
                 return new int[] {container.get(restValue),i};
             }
             else {
                 container.put(nums[i], i);
             }
         }
         return null;
    }

C实现

1:暴力法,时间复杂度o(n^2)

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* twoSum(int* nums, int numsSize, int target) {
    int *answer = (int *)malloc(sizeof(int) * 2);
    for(int i=0;i<numsSize-1;i++){
        for(int j=i+1;j<numsSize;j++){
            if(nums[i]+nums[j] == target){
                answer[0] = i;
                answer[1] = j;
                return answer;
            }
        }
    }
    return NULL;
}

算法题来自:https://leetcode-cn.com/problems/two-sum/description/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值