LeetCode 第一题解法

来源:互联网 发布:索尼卖大楼知乎 编辑:程序博客网 时间:2024/05/20 04:30
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
 public class problem1{
 public static int[] twoSum(int[]nums,int target)
 {
  int[] answer = new int[2];
  Map<Integer,Integer> hashmap = new HashMap();
  for(int i = 0; i < nums.length; i++)
  {
   if(hashmap.containsKey(nums[i]))
   {
    if(nums[i] + nums[i] == target)
    {
     answer[0] = hashmap.get(nums[i]);
     answer[1] = i;
     return answer;
    }
   }
   hashmap.put(nums[i], i);
  }
  List<Integer> list = new ArrayList<Integer>();
  for(int i : nums)
   list.add(i);
  list.add(target);
  Collections.sort(list); 
  while(true)
  {
   int a = list.get(0);
   int b = target - a;
   
   if(! hashmap.containsKey(b)) {
    list.remove(0);
    
    continue;
   }
   else if(hashmap.get(a) * 2 == target)
   {
    list.remove(0);
    continue;
   }
   else
   { 
    answer[0] = Math.min(hashmap.get(a), hashmap.get(b));
    answer[1] = Math.max(hashmap.get(a), hashmap.get(b));
    
                break;
   }
  }
  return answer;
  
 }
}
原创粉丝点击