Golang 2 pointers solution 9ms


  • 0
    R
    func sortTransformedArray(nums []int, a int, b int, c int) []int {
        aNums := make([]int ,0)
        for i:=0; i < len(nums); i++ {
            aNums = append(aNums, calculate(nums[i], a, b, c))
        }
        
    
        if a == 0 {
            if b > 0 {
                return aNums
            } else {
                for left, right := 0, len(aNums)-1; left < right; left, right = left+1, right-1 {
                    aNums[left], aNums[right] = aNums[right], aNums[left]
                }
                return aNums
            }
        } else {
            low := 0
            high := len(aNums) - 1
            ans := make([]int, 0)
            for low <= high {
                if (a > 0 && aNums[low] >= aNums[high]) || (a < 0 && aNums[low] <= aNums[high]) {
                    ans = append(ans, aNums[low])
                    low += 1
                } else {
                    ans = append(ans, aNums[high])
                    high -= 1
                }
            }
            
            if a > 0 {
                for left, right := 0, len(ans)-1; left < right; left, right = left+1, right-1 {
                    ans[left], ans[right] = ans[right], ans[left]
                }
                return ans
            } else {
                return ans
            }
        }
    }
    
    func calculate(num int, a int, b int, c int) int {
        return a*num*num + b * num + c 
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.