算法Android开发经验谈数据结构和算法分析

LeetCode 1

2018-11-24  本文已影响1人  旋哥

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");
    }
}
上一篇下一篇

猜你喜欢

热点阅读