zoukankan      html  css  js  c++  java
  • 第15题 三个数的和为确定值

    给出一组数:V = {-8,-4,-1,-1,0,0,0,0,0,1,2,5,7}

    找出所有和为0的三个元素的组合:[[-8, 1, 7], [-4, -1, 5], [-1, -1, 2], [-1, 0, 1], [0, 0, 0]]

    基本思路:

    先排序:{-8,-4,-1,-1,0,0,0,0,0,1,2,5,7}

    遍历:从最左边的第一个元素i=0开始,找到i=1~j=12之间两个数的和满足0-V[i]=V[m]+V[n],m从i+1开始,n从j=12开始。若0-V[i]<V[m]+V[n],则m++。若0-V[i]>V[m]+V[n],则j--

     

    注意:组合不能重复,故找到0-V[i]=V[m]+V[n]时,需要跳过V[m]右侧与V[m]相等的数,同理也要跳过所有V[n]左侧与V[n]相等的数。

     

    package T015;
    
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.HashSet;
    import java.util.List;
    
    public class ThreeSum {
        static List<List<Integer>> res =new ArrayList<List<Integer>>();
        public static void main(String[] args) {
            
            System.out.println(threeSum(new int[]{-8,-4,-1,-1,0,0,0,0,0,1,2,5,7}));
        }
    
        public static List<List<Integer>> threeSum(int[] nums) {
               Arrays.sort(nums);  
               for(int i=0;i<nums.length-2;i++){
                   if(i>0&&nums[i]==nums[i-1])   continue;   // to exclude the duplicated number
                   twoSum(0-nums[i],nums,i+1,nums.length-1);
               }
               return res;
            }
        private static void twoSum(int target,int[] nums, int start,int end){ 
               int i=start,j=end;
               while(i<j){
                   List<Integer> subres=new ArrayList<Integer>();
                   int sum=nums[i]+nums[j];
                   if(sum==target){
                        subres.add(0-target);
                        subres.add(nums[i]);
                        subres.add(nums[j]);
                        res.add(subres);
                       do {
                            i++;
                        }while(i < end && nums[i] == nums[i-1]);   // to exclude the duplicated number
                        do {
                            j--;
                        } while(j >= 0 && nums[j] == nums[j+1]); // to exclude the duplicated number
                    }
                    else if(sum<target) i++;
                    else j--;
                }
            }
            
        public static void printList(List<Integer> list){
            System.out.print("list: ");
            for(int i=0;i<list.size();i++){
                System.out.print(list.get(i)+" ");
            }
            System.out.println("");
        }
    }
  • 相关阅读:
    android WebView总结
    Java抓取网页数据(原网页+Javascript返回数据)
    Linux之旅(1): diff, patch和quilt (下)
    浅谈UML的概念和模型之UML九种图
    基于注解的Spring MVC
    Hibernate自增列保存失败的问题
    京东,你玩我?
    MySQL 通配符学习小结
    Java中怎样由枚举常量的ordinal值获得枚举常量对象
    HDU 4588 Count The Carries 计算二进制进位总数
  • 原文地址:https://www.cnblogs.com/wuchaodzxx/p/5853061.html
Copyright © 2011-2022 走看看