Leetcode 3
Array Easy + Medium
1. 121. Best Time to Buy and Sell Stock
一次买入一次卖出,求最大利润..
维护最小值,用buy保存下标,同时维护当前遍历得到的最大利润。
class Solution { public int maxProfit(int[] prices) { int buy = 0; int max = 0; for ( int i = 1; i < prices.length; i++ ){ if( prices[i] < prices[buy]){ buy = i; } else max = Math.max(max, prices[i] - prices[buy]); } return max; } }
2. Best Time to Buy and Sell Stock II
不限制次数,贪心算法,只要后一天比前一天价格高就买入,并累积利润。
1 class Solution { 2 public int maxProfit(int[] prices) { 3 int res = 0, temp = 0; 4 //greedy 5 for(int i = 1; i < prices.length ; i++){ 6 temp = prices[i] - prices[i-1]; 7 if( temp > 0) 8 res += temp; 9 } 10 return res; 11 } 12 }
3. 217. Contains Duplicate
出现两次及以上就可以返回true,采用HashMap键值对来反映,不断put,数组值对应key,下标对应value
并用containsKey判断是否有重复。
1 class Solution { 2 public boolean containsDuplicate(int[] nums) { 3 if( nums.length == 0 || nums.length == 1) 4 return false; 5 6 HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); 7 8 for( int i = 0 ; i < nums.length ; i++){ 9 if ( map.containsKey(nums[i])) 10 return true; 11 map.put(nums[i], i); 12 } 13 return false; 14 } 15 }
4. 219. Contains Duplicate II
数组内的nums[i] = nums[j]的同时,其下标i与j之差也不会超过k值。
if(map.containsKey(nums[i]) && i - map.get(nums[i]) <= k)
1 class Solution { 2 public boolean containsNearbyDuplicate(int[] nums, int k) { 3 4 HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); 5 for(int i = 0 ; i < nums.length; i ++){ 6 if(map.containsKey(nums[i]) && i - map.get(nums[i]) <= k) 7 return true; 8 9 map.put(nums[i], i); 10 } 11 return false; 12 } 13 }
5. 11. Container With Most Water (Medium)
两个坐标left和right分别从两头开始,当height[left] < height[right]时,left++ 否则right--
1 class Solution { 2 public int maxArea(int[] height) { 3 int left = 0, right = height.length -1; 4 int res = 0; 5 while( left != right ){ 6 int tempArea = (right - left) * Math.min(height[left], height[right]); 7 res = Math.max(res, tempArea); 8 if(height[left] < height[right]) 9 left++; 10 else 11 right--; 12 } 13 return res; 14 } 15 }