Andreea

Given a 2D integer array matrix, return the transpose of matrix.

The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix’s row and column indices.

Example 1:

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[1,4,7],[2,5,8],[3,6,9]]

Example 2:

Input: matrix = [[1,2,3],[4,5,6]]
Output: [[1,4],[2,5],[3,6]]
class Solution {
public:
vector<vector<int>> transpose(vector<vector<int>>& matrix) {

int row = matrix.size();
int column = matrix[0].size();

vector<vector<int>> ans(column, vector<int>(row, 0));

for(int i=0; i<row; i++){

for(int j=0; j<column; j++){

ans[j][i]=matrix[i][j];
}
}
return ans;
}
};

Runtime: 12 ms, faster than 67.75% of C++ online submissions for Transpose Matrix.

Memory Usage: 10.4 MB, less than 99.73% of C++ online submissions for Transpose Matrix.

--

--

Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.

You must implement a solution with a linear runtime complexity and use only constant extra space.

Example 1:

Input: nums = [2,2,1]
Output: 1

Example 2:

Input: nums = [4,1,2,1,2]
Output: 4

Example 3:

Input: nums = [1]
Output: 1

constant extra space

題目限制不會變動的空間,例如array,會變動的空間像是vector的push_back就不行。

解法一

class Solution {
public:
int singleNumber(vector<int>& nums) {

int arr_pos[3*10000+1] = {0};
int arr_neg[3*10000] = {0};

for(int i=0; i<nums.size(); i++){
if(nums[i] >= 0){
arr_pos[nums[i]]++;
}
else{
arr_neg[-(nums[i])]++;
}
}

for(int i=0; i<=3*10000; i++){
if(arr_pos[i] == 1){
return i;
}

if(arr_neg[i] == 1){
return -i;
}
}
return 0;
}
};

解法二

使用XOR

XOR Truth Table

以example 2為例:

Input: nums = [4,1,2,1,2]
Output: 4

由左至右,計算如下,有黃色標示為輸入數字,未標示者為res

--

--

Spinner 下拉式選單

  1. 在strings.xml中建立字串陣列,再將此字串陣列設定給spinner元件成為選單
<resources>
<string name="app_name">spinner</string>
<string-array name="gender_list">
<item>男生</item>
<item>女生</item>
</string-array>
</resources>

2. 在介面布局檔(activity_main.xml)中加入spinner元件,並設定好屬性

<Spinner
android:id="@+id/spnGender"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:entries="@array/gender_list" />

3. MainActivity.java中取得spiinner元件,並設定處理程序

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Spinner mspnGender = findViewById(R.id.spnGender);
mspnGender.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//選擇選項要做的事
switch (position){
case 0:
mGender = "男生";
break;
case 1:
mGender = "";
break;
}
}

@Override
public void onNothingSelected(AdapterView<?> parent) {
//沒有選擇選項要做的事
}
});

--

--