leetcode two sum 排序+二分 Onlogn

排序+二分

class Solution {
    class pair
    {
        int x,y;
        public pair(int a,int b)
        {
            x=a;y=b;
        }
    }
    pair p[]=new pair[10005];
    class mcomp implements Comparator<pair>
    {
        public int compare(pair a,pair b)
        {
            if(a.x!=b.x)
            return a.x-b.x;
            else
            return a.y-b.y;
        }
    }
    public int[] twoSum(int[] nums, int target) {
          int[] jieguo=new int[2];
          jieguo[0]=10;
          jieguo[1]=10;
          for(int i=0;i<nums.length;++i)
          {
                p[i]=new pair(nums[i],i);
          }
          Arrays.sort(p,0,nums.length,new mcomp());
          for(int i=0;i<nums.length-1;++i)
          {
              int l=i+1,r=nums.length-1;
              int t=target-p[i].x;
              while(l<r)
              {
                  int mid=l+r>>1;
                  if(p[mid].x>=t)r=mid;
                  else l=mid+1;
              }
              if(p[l].x==t)
              {
                  jieguo[0]=p[i].y;
                  jieguo[1]=p[l].y;
              }
          }
          return jieguo;
    }
}

哈希

import java.util.HashMap;

public class Solution {
	public int[] twoSum(int[] nums, int target) {
        int[] jieguo=new int[2];//定义一个空白的,含有2个位置的数组
        HashMap<Integer,Integer> map =new HashMap<Integer,Integer>();
        for(int i=0;i<nums.length;++i)
        {
            if(map.containsKey(target-nums[i]))
            {
            	return new int[]{map.get(target-nums[i]),i};
            }
            else
            {
            	map.put(nums[i], i);
            }
        }
        return jieguo;
  }
}

posted @ 2022-11-17 23:03  林动  阅读(13)  评论(0编辑  收藏  举报