3 Sum Closest
public int threeSumClosest(int[] numbers ,int target) { // write your code here int minEr = Integer.MAX_VALUE; int ret = 0; Arrays.sort(numbers); for (int i = 1; i < numbers.length - 1; ++i) { int p1 = 0, p2 = numbers.length - 1; while (p1 < i && p2 > i) { int s1 = numbers[p1] + numbers[p2] + numbers[i] - target; if (Math.abs(s1) < minEr) { minEr = Math.abs(s1); ret = numbers[p1] + numbers[p2] + numbers[i]; } if (s1 > 0) { --p2; } else if (s1 < 0) { ++p1; } else { return target; } } } return ret; }
public ArrayList<ArrayList<Integer>> threeSum(int[] numbers) { // write your code here ArrayList<ArrayList<Integer>> ret = new ArrayList<ArrayList<Integer>>(); Arrays.sort(numbers); ArrayList<String> mp = new ArrayList<>(); for (int i = 1; i < numbers.length - 1; ++i) { int p1 = 0, p2 = numbers.length - 1; while (p1 < i && p2 > i) { int sum = numbers[i] + numbers[p1] + numbers[p2]; if (sum > 0) { --p2; } else if (sum < 0) { ++p1; } else { ArrayList<Integer> ad = new ArrayList<>(); String tag = numbers[p1] + "#" + numbers[i] + "#" + numbers[p2]; if (!mp.contains(tag)) { ad.add(numbers[p1]); ad.add(numbers[i]); ad.add(numbers[p2]); ret.add(ad); mp.add(tag); } --p2; ++p1; } } } return ret; }
C++:
vector<vector<int> > threeSum(vector<int> &nums) { // write your code here vector<vector<int> > result; sort(nums.begin(), nums.end()); for (int i = 0; i < nums.size(); ++i) { if (i > 0 && nums[i] == nums[i - 1]) { continue; } int left = i + 1; int right = nums.size() - 1; while (left < right) { int sum = nums[i] + nums[left] + nums[right]; if (sum < 0) { ++left; } else if (sum > 0) { --right; } else { vector<int> triple; triple.push_back(nums[i]); triple.push_back(nums[left]); triple.push_back(nums[right]); result.push_back(triple); ++left; --right; while (left < right && nums[left - 1] == nums[left]) { ++left; } while (left < right && nums[right] == nums[right + 1]) { ++right; } } } } return result; }
Partition Array
这地方写了一年都没写对,得去练练怎么写快排了
int partitionArray(vector<int> &nums, int k) { // write your code here int i = 0, j = nums.size() - 1; while (i <= j) { while (i <= j && nums[i] < k) ++i; while (i <= j && nums[j] >= k) --j; if (i <= j) { int tmp = nums[i]; nums[i] = nums[j]; nums[j] = tmp; ++i; --j; } } return i; }
总想把每一篇文章精雕细琢之后以完美的面貌示人,就像演员在演出前都要彩排,总想准备好之后再去展现精彩的一面,但人生的每一刻都是精彩的,就算现在还不完善也要发出来,作为自己一直在学习的一种见证。