• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
beily leetcode
博客园    首页    新随笔    联系   管理    订阅  订阅
1. Two Sum I & II & III

1. Given an array of integers, return indices of the two numbers such that they add up to a specific target.

问题:

1.数组是否有序

2. 数组排序

// sorting array
   Arrays.sort(iArr)

方法1:O(n^2)

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

 2. Two sum II  Input array is sorted (HashMap, 无相同元素

Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

 

 

public class Solution {
    public int[] twoSum(int[] nums, int target) {
int [] result = new int[2]; HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>(); for(int i = 0; i < nums.length; i++){ hm.put(nums[i], i); } for(int i = 0; i < nums.length; i++){ if(hm.containsKey(target-nums[i]) && target != 2 * nums[i]){ result[0] = i; result[1] = hm.get(target-nums[i]); break; } } return result; }
}

3. Two sum III  

 

posted on 2016-07-19 05:24  beily  阅读(106)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3