数组串联
给你一个长度为 n 的整数数组 nums 。请你构建一个长度为 2n 的答案数组 ans ,数组下标 从 0 开始计数 ,对于所有 0 <= i < n 的 i ,满足下述所有要求:
ans[i] == nums[i]
ans[i + n] == nums[i]
具体而言,ans 由两个 nums 数组 串联 形成。
返回数组 ans 。
示例 1:
输入:nums = [1,2,1]
输出:[1,2,1,1,2,1] 解释:数组 ans 按下述方式形成:
- ans = [nums[0],nums[1],nums[2],nums[0],nums[1],nums[2]]
- ans = [1,2,1,1,2,1]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/concatenation-of-array
新申请一个数组空间,将nums的内容拷贝两份即可。在遍历过程中,新数组的对应位置应该是nums数组中i对数组长度取余得到的索引。
class Solution {
public int[] getConcatenation(int[] nums) {
int[] a = new int[nums.length*2];
for(int i=0;i<nums.length*2;i++){
a[i] = nums[i%nums.length];
}
return a;
}
}
执行操作后变量值
存在一种仅支持 4 种操作和 1 个变量 X 的编程语言:
++X 和 X++ 使变量 X 的值 加 1
–X 和 X-- 使变量 X 的值 减 1
最初,X 的值是 0
给你一个字符串数组 operations ,这是由操作组成的一个列表,返回执行所有操作后, X 的 最终值 。
示例 1:
输入:operations = [“–X”,“X++”,“X++”]
输出:1
解释:操作按下述步骤执行:
最初,X = 0
–X:X 减 1 ,X = 0 - 1 = -1
X++:X 加 1 ,X = -1 + 1 = 0
X++:X 加 1 ,X = 0 + 1 = 1
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/final-value-of-variable-after-performing-operations
class Solution {
public int finalValueAfterOperations(String[] operations) {
int x=0;
for(int i=0;i<operations.length;i++){
if(operations[i].equals("++X")||operations[i].equals("X++")){
x++;
}
else
x--;
}
return x;
}
}
比较简单,就是遍历字符串数组,看数组中的元素与++X,X++是否匹配,匹配的话x++;否则x–。