subarray Sum Closest
1. Save <sum[i + 1], i>, and then sort Sum[i + 1], and then find the minimum difference between adjacent values.
2. Treemap:ceilingentry returns a key-value mapping relationship that associates value with a minimum key greater than or equal to the given key. Floorentry: Returns the maximum key association value that is less than or equal to the given key.
PublicArraylist<integer> Subarraysumclosest (int[] nums) { //Write your code herearraylist<integer> res =NewArraylist<integer>(); if(Nums = =NULL|| Nums.length = = 0) { returnRes; } TreeMap<integer, integer> map =NewTreemap<integer, integer>(); intsum = 0; intMindif =Integer.max_value; Res.add (0); Res.add (0); for(inti = 0; i < nums.length; ++i) {sum+=Nums[i]; Map.entry Floor=map.floorentry (sum); Map.entry Ceiling=map.ceilingentry (sum); if(Floor! =NULL|| Ceiling! =NULL) { if(Floor = =NULL|| (Ceiling! =NULL&& Math.Abs ((int) Floor.getkey ()-sum) > Math.Abs ((int) Ceiling.getkey ()-sum))) { if(Math.Abs (int) Ceiling.getkey ()-sum) <mindif) {Res.set (0, (int) Ceiling.getvalue () + 1); Res.set (1, i); Mindif= Math.Abs ((int) Ceiling.getkey ()-sum); } } Else { if(Math.Abs (int) Floor.getkey ()-sum) <mindif) {Res.set (0, (int) Floor.getvalue () + 1); Res.set (1, i); Mindif= Math.Abs ((int) Floor.getkey ()-sum); }}} map.put (sum, i); } returnRes; }
7-4 Day Brush problem