leetcode八分钟补完三天的每日一题哈哈哈哈
主打一个求同存异

- import java.util.Arrays;
-
- class Solution {
- public int singleNumber(int[] nums) {
- Arrays.sort(nums);
- int ans = 0;
- for (int i = 0; i < nums.length; ) {
- try {
- if (nums[i] == nums[i + 1]) {
- i += 2;
- } else {
- ans = nums[i];
- break;
- }
- } catch (Exception e) {
- ans = nums[nums.length - 1];
- break;
- }
-
- }
-
- return ans;
- }
- }

- import java.util.Arrays;
-
- class Solution {
- public int singleNumber(int[] nums) {
- Arrays.sort(nums);
- int ans = 0;
- for (int i = 0; i < nums.length; ) {
- try {
- if (nums[i] == nums[i + 1] && nums[i] == nums[i + 2]) {
- i += 3;
- } else {
- ans = nums[i];
- break;
- }
- } catch (Exception e) {
- ans = nums[nums.length - 1];
- break;
- }
-
- }
- return ans;
- }
- }

- import java.util.Arrays;
-
- class Solution {
- public int[] singleNumber(int[] nums) {
- Arrays.sort(nums);
- int ans[] =new int[2],cnt=0;
- for (int i = 0; i < nums.length; ) {
- try {
- if (nums[i] == nums[i + 1] ) {
- i += 2;
- } else {
- ans[cnt++] = nums[i];
- i++;
- }
- } catch (Exception e) {
- if(cnt<2)
- {
- ans[cnt++] = nums[nums.length - 1];
- }
- break;
- }
- }
- return ans;
- }
- }
一段代码稍加修改即可。
思路:直接在原数组nums上遍历,如果下标i和下标为i+1的元素相同则继续,并且i+=2,否则返回当前元素。如果是三个元素相同那就判断三个,如果是有两个只有一个的元素,那就继续遍历,直到记录当前元素的cnt为2为止。
再说说数组越界问题,使用try{}catch(){},是真的好用呜呜呜,以前写c++的时候感觉都是自己手写,(也许是我水平太低),反正有了第一次就会有无数次的真香。
今天操作系统实验写c的时候,恍然发现我已经连c的头文件都忘记怎么写的了,,,哈哈哈哈哈哈(失声痛哭)