zoukankan      html  css  js  c++  java
  • Two Sum

    1.hashMap方法O(n)空间换时间

    public class Solution {
        public int[] twoSum(int[] numbers, int target) {
            HashMap<Integer,Integer> hash=new HashMap<Integer,Integer>();
            int ans[]=new int[2];
            for(int i=0;i<numbers.length;i++)
            {
                if(hash.containsKey(target-numbers[i]))
                {
                    ans[0]=hash.get(target-numbers[i])+1;
                    ans[1]=i+1;
                    return ans;
                    
                }
                else hash.put(numbers[i],i);
                
            }
                
            
            return ans;
        }
    }
    View Code

    2. 排序后获取两个值

    class node implements Comparable<node>
    {
        int x;
        int y;
        public int compareTo(node n)
        {
            return this.x-n.x;
            
            
        }
        public node(int x,int y)
        {
            this.x=x;
            this.y=y;
            
        }
    }
    public class Solution {
        
        public int[] twoSum(int[] numbers, int target) {
            node n[]=new node[numbers.length];
            for(int j=0;j<numbers.length;j++)
            {
                n[j]=new node(numbers[j],j+1);
            }
            Arrays.sort(n);
                
            
            int ans[]=new int[2];
            int low=0;
            int high=numbers.length-1;
            while(low<high)
            {
                int sum=n[low].x+n[high].x;
                if(sum==target)
                {
                    ans[0]=n[low].y;
                    ans[1]=n[high].y;
                    if(n[low].y>n[high].y)
                    {
                        ans[0]=n[high].y;
                        ans[1]=n[low].y;
                    }
               
                 break;
                }
                else if(sum>target) high--;
                else  low++;
               
                
                
                
            }
            
            return ans;
           
        }
    }
  • 相关阅读:
    【.NET】Web Service
    【Coding】C# 操作文件(一)
    【设计模式】设计模式概述
    TCP/IP协议
    【.NET】SOAP Web Service
    简单读写xml
    利用winform来承载WCF服务
    在panel里面显示一个窗体
    asp.net 角色管理 MSDN帮助路径
    asp.net ajax MSDN帮助
  • 原文地址:https://www.cnblogs.com/hansongjiang/p/3864087.html
Copyright © 2011-2022 走看看