今天搜寒冬的面试杀手题——大草原,发现是以前的机试第四题,这道题跪了让我后悔一生。到现在我唯一知道的是这道题可以用贪心算法骗分。
http://stackoverflow.com/questions/15882202/minimum-number-of-circles-with-radius-r-to-cover-n-points
凭我多年的经验,以后还会遇到这题,如果不解决的话,以后还是会在这上面跪一次。一定要好好学学计算几何的算法。
Remove Duplicates from Sorted Array II
这题真是easy级别的吗?我都写的吐血了,最后用极其丑陋的方法解决了。
public int removeDuplicates(int[] nums) { // write your code here int sum = 0; HashMap<Integer, Integer> mp = new HashMap<>(); for (int i = 0; i < nums.length; ++i) { if (!mp.containsKey(nums[i])) { mp.put(nums[i], 1); sum += 1; } else { int num = mp.get(nums[i]); mp.put(nums[i], num + 1); if (num + 1 == 2) { sum += 1; } } } int pos = 0; int[] n = new int[sum]; for (Integer key : mp.keySet()) { int num = mp.get(key); if (num == 1) { n[pos++] = key; } else if (num >= 2) { n[pos++] = key; n[pos++] = key; } } Arrays.sort(n); for (int i = 0; i < sum; ++i) { nums[i] = n[i]; } return sum; }
前几天是中二了吗?为啥这么水的题都写不出来,看来是Java使用过度了,不用List和Map就不舒服。
int removeDuplicates(vector<int> &nums) { // write your code here if (nums.size() == 0) { return 0; } int k = 1, p = 0, ti = 1; for (int i = 1; i < nums.size(); ++i) { if (nums[i] != nums[i - 1]) { ti = 1; nums[k++] = nums[i]; } else { ++ti; if (ti <= 2) { nums[k++] = nums[i]; } } } return k; }