1. 程式人生 > 其它 >python使用SQLAlchemy操作資料庫

python使用SQLAlchemy操作資料庫

技術標籤:刷題

難度:中等。
標籤:陣列,雙指標。
將上一題的程式碼改一改就可以了。

正確解法:

class Solution {

    int my_abs(int a){
        return a>=0?a:-a;
    }

public:
    int threeSumClosest(vector<int>& nums, int target) {
        int n = nums.size();
        if(n == 3)return (nums[0] + nums[1] + nums[2]);
        sort
(nums.begin(), nums.end()); int result = nums[0] + nums[1] + nums[2]; int distance = my_abs(result - target); int k = 0; while(k < n - 2){ if(k != 0){ if(nums[k - 1] == nums[k]){ k++; continue; }
} int left = k + 1, right = n - 1; while(left < right){ int temp = nums[k] + nums[left] + nums[right]; if(my_abs(temp - target) < distance){ result = temp; distance = my_abs(result - target)
; } if(temp - target > 0){ right--; while(nums[right] == nums[right + 1] && right > 0)right--; } else if(temp - target < 0){ left++; while(nums[left] == nums[left - 1] && left < n - 1)left++; } else{ return target; } } k++; } return result; } };

在這裡插入圖片描述