TwoSum

题目:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

try:

public class Solution {
    public int[] twoSum(int[] nums, int target) {
         int sum=0;
         int[] index=new int[2];  //预先声明不必
         int x=0;
         int y=0;

         ok:
         for(int i = 0;i<nums.length;i++){
             for(int j=0;j<nums.length;j++){
                 if(i==j){
                     continue;
                 }else{
                     sum=nums[i]+nums[j];
                     x=i;
                     y=j;
                 }
                if(sum==target){
                     break ok;
                 }

             }

         }

         index[0]=x;
         index[1]=y;

         return index;
    }
}

ok, break ok 跳出多重循环

几个算法:
1、brute-force: 单匹配算法,基本思路:从目标串的第一个字符与模式串中的第一个字符比较,若相等,则继续逐个比较后续字符,否则从目标串的第二个字符开始重新与模式串的第一个字符进行比较。以此类推。若从模式串的第I个字符开始,每个字符一次和目标串t中的对应字符相等,则匹配成功,该算法返回位置,否则匹配失败返回-1.

public class solution{
   public class int[] twoSum(int[] nums, int target){
      for(int i=0;i<nums.lenth;i++){
         for(int j=i+1;j<nums.length;j++){
         if(nums[j]==target-nums[i]){
           return int[]{i,j};   }  //返回一个数组的表达方式
         }
      }
      throw new IllegalArgumentException("No two sum solution");  //若不存在符合的数,要抛出异常
   }
}

其中时间复杂度为O(n^2)。

2、One pass hash table(?)
采用map , map.containsKey:
Returns true if this map contains a mapping for the specified key.

public int[] twoSumNew(int[] nums, int target){
    Map<Integer, Integer> map =new HashMap<>();
    for(int i=0; i<nums.length;i++){
        int number=target-nums[i];
        if(map.containsKey(number)){
            return new int[]{map.get(number),i};
        }
    }
    throw new IllegalArgumentException("No two sum solution");
    }
}

时间复杂度为O(n)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值