diff --git a/disappearednumbers.cpp b/disappearednumbers.cpp new file mode 100644 index 00000000..10564c83 --- /dev/null +++ b/disappearednumbers.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + vector findDisappearedNumbers(vector& nums) { + vector result;// array to store the missing numbers + int n = nums.size(); + for(int i = 0 ; i < n ; i++){ + int index = abs(nums[i]) - 1; // get the index corresponding to the current number + if(nums[index] > 0){ + nums[index] *= -1;//if +ve make it -ve + } + } + for(int i = 0 ; i < n ; i++){ + if(nums[i]>0){ + result.push_back(i+1);//if +ve add to the result array + }else{ + nums[i] *= -1;//restores the values back to +ve + } + } + return result; + + } +}; \ No newline at end of file diff --git a/gameoflife.cpp b/gameoflife.cpp new file mode 100644 index 00000000..7d9a2191 --- /dev/null +++ b/gameoflife.cpp @@ -0,0 +1,54 @@ +class Solution { +public: + void gameOfLife(vector>& board) { + int m = board.size(); + int n = board[0].size(); + + for(int i = 0 ; i < m ; i++){ + for(int j = 0 ; j < n ; j++){ + int count = countalive(board,i,j); + + if((board[i][j] == 1) && (count < 2 || count > 3)){ + board[i][j] = 2; + } + if((board[i][j] == 0) && (count == 3)){ + board[i][j] = 3; + } + } + } + + for(int i = 0 ; i < m ; i++){ + for(int j = 0 ; j < n ; j++){ + if(board[i][j] == 2){ + board[i][j] = 0; + } + if(board[i][j] == 3){ + board[i][j] = 1; + } + } + } + } + +private : + int countalive(vector>& board,int i,int j){ + int count = 0; + + + vector> direction = { + {0,-1},{-1,0},{1,0}, + {-1,-1},{-1,1},{1,-1},{1,1},{0,1} + }; + + for(auto &dir : direction){ + int nrow = i + dir[0]; + int ncolumn = j + dir[1]; + + if(nrow >= 0 && ncolumn >= 0 && + nrow < board.size() && ncolumn < board[0].size() && + (board[nrow][ncolumn] == 1 || board[nrow][ncolumn] == 2)){ + count++; + } + } + return count; + } +};