将时间复杂度由n4次方降到n2次方

来源:互联网 发布:php商城源码带支付 编辑:程序博客网 时间:2024/06/07 03:14
public int threeSumClosest(int[] nums , int target) {     int res = 0;     int tmp = 0;     int lastspace = 0;     boolean flag = true;     Arrays.sort(nums);     for(int i = 0 ; i < nums.length ; i++){         int j = i + 1;         int z = nums.length -1;         while(j < z){             tmp = nums[i] + nums[j] + nums[z];             if(Math.abs(tmp - target) < lastspace || (lastspace == 0 && flag)){                lastspace = Math.abs(tmp - target);                res = tmp;                 if(tmp - target < 0){                    j++;                 }else{                    z--;                 }                flag = false;             }else{                    if(lastspace +  target <= nums[i] + nums[j + 1] + nums[z]){                        z--;                    }else{                        j++;                    }             }         }     }     return res; }
原创粉丝点击