LeetCode 1

6 篇文章 0 订阅
1 篇文章 0 订阅

###Two Sum

题目描述

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].

C语言实现

通过最简单的方式,两个下标,先保持一个下标i不动,另一个下标j从第一个下标后一个开始移动,j移动到最后一个后,开始移动第一个下标i

#include<stdio.h>
//时间复杂度 O(n^2) 
int* twoSum(int* nums, int numsSize, int target) {
    int i,j;
    int * indices = (int*)malloc(2*sizeof(int));
    for(i=0;i<numsSize;i++){           
        for(j=i+1;j<numsSize;j++){      
            if(nums[i]+nums[j] == target){
                *indices = i;
                *(indices+1)= j;
                break;
            } 
        }
    }

    return indices;
}
//测试代码
int main(){
	int i;
	int a[5] = {2,7,11,15};
	int *p = twoSum(a,5,9);
	for(i=0;i<2;i++){
		printf("%d ",*(p+i));
	}
	return 0;
	
}

Java实现(优化过)

使用Map集合,Map里存储目标值与数组值之差target-num[i] 和 下标 i,然后判断num[i]是否在Map的key中,不在时继续存储,在时就是所找目标值。
这种方式时间复杂度为O(n),执行效率大大提高。

public class One {
    public static void main(String[] args) {
        One one = new One();
        int[] array = one.twoSum(new int[]{2, 7, 11, 15},10);
        System.out.println(Arrays.toString(array));
    }

    public int[] twoSum(int[] nums, int target) {
        Map<Integer,Integer> map = new HashMap<>();

        for (int i = 0; i < nums.length; i++) {
            if(!map.containsKey(nums[i])){
                map.put(target-nums[i],i);
            }else {
                return new int[]{i,map.get(nums[i])};
            }
        }

        throw new RuntimeException("no exist");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值