【leetCode】のTwo Sum
インターンシップを探してみようと思ったら、そろそろ閉会して問題を修正します.
leetCodeの1つ目を見て、本当に大学の基礎を全部忘れてしまった【ため息.jpg】
間違いは百出だが、まとめてみると:
タイトル:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
大学の接触が比較的に多いのはC++関連コードで、問題を解く構想:
同じ配列に2数の和が存在するか否かが目標値であることが要求されるため,2つの変数i,jで配列下標を格納する.nums[i]+nums[j]をtargetと比較し、同じように返す.
もちろん、私は何度も間違いを提出しました.記録は以下の通りです.
1.
Runtime Error Message: AddressSanitizer: heap-buffer-overflow on address 0x6020000000bc at pc 0x0000004060a6 bp 0x7ffd786a6100 sp 0x7ffd786a60f8
Last executed input: [3,2,4] 6
エラー原因:下付き参照エラー、配列長sizeof(nums)/sizeof(nums[0])で計算した、エラー、変更=>nums.size()
2.
Wrong Answer:
Input: [0,4,3,0] 0
Output: []
Expected: [0,3]
エラー原因:考慮が不十分で、サイクルを少なくするために、if(nums[i]>=target)continueという2層のサイクルに条件を設定しました.//蛇に足を添える!!
3.
Wrong Answer:
Input: [-3,4,3,90] 0
Output: []
Expected: [0,2]
エラー原因:前のステップでは0を考えていなかったので、今回は複数を考えていないので、so~
正しいC++コード:
python 3コード:
JAvaはあまり详しくなくて、后で勉强して更新に来て、しかし时空の上の消耗はすべてC++が少なくて、もちろんpythonのコードは本当に短いです~
leetCodeの1つ目を見て、本当に大学の基礎を全部忘れてしまった【ため息.jpg】
間違いは百出だが、まとめてみると:
タイトル:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
大学の接触が比較的に多いのはC++関連コードで、問題を解く構想:
同じ配列に2数の和が存在するか否かが目標値であることが要求されるため,2つの変数i,jで配列下標を格納する.nums[i]+nums[j]をtargetと比較し、同じように返す.
もちろん、私は何度も間違いを提出しました.記録は以下の通りです.
1.
Runtime Error Message: AddressSanitizer: heap-buffer-overflow on address 0x6020000000bc at pc 0x0000004060a6 bp 0x7ffd786a6100 sp 0x7ffd786a60f8
Last executed input: [3,2,4] 6
エラー原因:下付き参照エラー、配列長sizeof(nums)/sizeof(nums[0])で計算した、エラー、変更=>nums.size()
2.
Wrong Answer:
Input: [0,4,3,0] 0
Output: []
Expected: [0,3]
エラー原因:考慮が不十分で、サイクルを少なくするために、if(nums[i]>=target)continueという2層のサイクルに条件を設定しました.//蛇に足を添える!!
3.
Wrong Answer:
Input: [-3,4,3,90] 0
Output: []
Expected: [0,2]
エラー原因:前のステップでは0を考えていなかったので、今回は複数を考えていないので、so~
正しいC++コード:
class Solution {
public:
vector twoSum(vector& nums, int target) {
//int len = sizeof(nums) / sizeof(nums[0]);
int len = nums.size();
vector res; // vector
for(int i=0;i target) continue;
for(int j=i+1;j target) continue;
if(nums[i] + nums[j] == target){ //
//
res.push_back(i);
res.push_back(j);
return res;
}
}
}
return res;
}
};
python 3コード:
class Solution:
def twoSum(self, nums: 'List[int]', target: 'int') -> 'List[int]':
for k in range(len(nums)):
for l in range(k+1,len(nums)):
if nums[k] + nums[l] == target:
return [k,l]
JAvaはあまり详しくなくて、后で勉强して更新に来て、しかし时空の上の消耗はすべてC++が少なくて、もちろんpythonのコードは本当に短いです~