LeetCode1-Two Sum
2016-07-25 23:46
309 查看
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
题目:给定一数组,输出满足条件的数组下标,实现的思想比较简单,先实现排序,然后采用start、end下标遍历满足条件的下标。
/* * time:2016-7-25 22:08:24 * location:home * */ import java.util.Arrays; public class Solution { public static int[] twoSum(int[] nums, int target){ // int[] res = new int[2]; // res[0] = -1; // res[1] = -1; // // final HashMap<Integer, Integer> h = new HashMap<Integer,Integer>(); // // for(int i = 0; i < nums.length; i++){ // if(h.containsKey(target - nums[i])){ // int index = h.get(target-nums[i])+1; // res[0] = Math.min(i+1, index); // res[1] = Math.max(i+1, index); // } // h.put(nums[i],i); // } // // return res; //O(nlogn) int a = 0, b=0; int start = 0, end = nums.length-1; int [] nums2 = Arrays.copyOf(nums, nums.length); Arrays.sort(nums2); //find the nums,头尾指针 while(start < end){ int sum = nums2[start] + nums2[end]; if(sum < target){ start++; } else if(sum > target){ end--; } else{ a = nums2[start]; b = nums2[end]; break; } } //find the index of the nums int[] res = new int[2]; for(int i = 0; i < nums.length; i++){ if(nums[i] == a){ res[0] = i; break; } } if(a != b){ for(int i =0; i < nums.length; i++){ if(nums[i] == b){ res[1] = i; break; } } } else { for(int i = 0; i < nums.length; i++){ if(nums[i] ==b && i != res[0]){ res[1] = i; break; } } } return res; } //test public static void main(String[] args){ int[] nums = {3,2,2,7,7,8,11,15}; int tagert = 9; int[] result = twoSum(nums,tagert); for(int i=0; i < result.length; i++){ System.out.println("res[i]"+result[i]); } } // public int[] TwoSum(int[] nums, int target){ // // } }代码参考leetcode discussion
相关文章推荐
- POJ 2082 Terrible Sets(单调栈)
- mkimage
- 漫话中国古代史 —— 总论
- python的学习笔记
- iptables
- hdoj1873看病要排队(优先队列)
- CDH中服务的配置及启动
- Lua 基础
- 7月25日实习日志
- android 广告轮播位Banner轮播位 使用超级方便
- scala基础25-闭包
- 服务器TIME_WAIT和CLOSE_WAIT详解和解决办法
- netty对http协议解析原理解析
- netty对http协议解析原理解析
- netty对http协议解析原理
- 【Java】LeetCode进阶之路(Swap Nodes in Pairs)
- gitlab 邮件配置(smtp)
- py_Django之表单
- 北京第一天
- php环境配置