无法将类型“()”的值分配给类型“ [Int]”

时间:2018-10-08 20:58:21

标签: swift

给出一个非负整数数组A,返回一个数组,该数组包含A的所有偶数元素,后跟A的所有奇数元素。

Input: [3,1,2,4]
Output: [2,4,3,1]
The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.

我已经实现了以下操作,但是却抛出了错误

  

第17行:无法将类型为(()'的值分配给类型为[[Int]'

顺便问一下,还有更优雅的解决方案吗?

class Solution {
    func sortArrayByParity(_ A: [Int]) -> [Int] {
        var oddTemp :[Int] = []
        var evenTemp :[Int] = []

        for a in A
        {
            if a%2 == 0
            {
                evenTemp.append(a)
            }
            else
            {
                oddTemp.append(a)
            }
        }
        // error is thrown in the following
        return evenTemp += oddTemp         
    }
}

4 个答案:

答案 0 :(得分:2)

如果要变异原始数组:

from selenium import webdriver

browser = webdriver.Firefox()
try:
    browser.get("https://campus.webex.com/mw3100/mywebex/default.do?siteurl=campus&service=7")
except:
    print("pagina non trovata")

try:
    utente=browser.find_element_by_name("userName")
except:
    print("elemento non trovato")    
else:
    print(utente)
    utente.send_keys('user@gestione.eu')
try:
    psw=browser.find_element_by_name("PASSWD")
except:
    print("elemento non trovato")    
else:
    print(psw)
    psw.send_keys('123456')

如果您喜欢不变性:

var a = [3, 1, 2, 4]
a.sort(by: { $0 % 2 < $1 % 2 })
print(a)  //prints [2, 4, 3, 1]

其他解决方案:

let a = [3, 1, 2, 4]
let result: [Int] = a.sorted(by: { $0 % 2 < $1 % 2})
print(result)  //prints [2, 4, 3, 1]

打印let a = [3,1,2,4] let result: [Int] = a.reduce(into: []) { accumulator, element in let newIndex = element % 2 == 0 ? accumulator.startIndex : accumulator.endIndex accumulator.insert(element, at: newIndex) } print(result)

答案 1 :(得分:2)

return evenTemp + oddTemp

做您想要的事

可变数组可以就地排序,例如以您的示例为例

var a = [0, 3, 1, 2, 4, 5, 6, 6, 7, 7, 8,9,10,10,11,11,11,11,12]
a.sort { $1 % 2 > $0 % 2 }
print(a) // [0, 2, 4, 6, 6, 8, 10, 10, 12, 3, 1, 5, 7, 7, 9, 11, 11, 11, 11]

答案 2 :(得分:1)

+=运算符使左侧操作数突变,其返回值为Void。您需要将数组的连接和return语句分成单独的行。

evenTemp += oddTemp
return evenTemp

答案 3 :(得分:1)

evenTemp += oddTemp 

不返回任何内容

evenTemp += oddTemp 
return evenTemp